How to resolve the algorithm Sum and product of an array step by step in the Picat programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sum and product of an array step by step in the Picat programming language

Table of Contents

Problem Statement

Compute the sum and product of an array of integers.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sum and product of an array step by step in the Picat programming language

Source code in the picat programming language

go =>
  L = 1..10,
  println(sum=sum(L)),  
  println(prod=prod(L)),  
  nl,
  println(sum_reduce=reduce(+,L)),  
  println(prod_reduce=reduce(*,L)),  
  println(sum_reduce=reduce(+,L,0)),  
  println(prod_reduce=reduce(*,L,1)),  
  nl,
  println(sum_fold=fold(+,0,L)),  
  println(prod_fold=fold(*,1,L)),  
  nl,
  println(sum_rec=sum_rec(L)),  
  println(prod_rec=prod_rec(L)),

  nl.

% recursive variants
sum_rec(List) = Sum =>
  sum_rec(List,0,Sum).
sum_rec([],Sum0,Sum) => 
  Sum=Sum0.
sum_rec([H|T], Sum0,Sum) =>
  sum_rec(T, H+Sum0,Sum).

prod_rec(List) = Prod =>
  prod_rec(List,1,Prod).
prod_rec([],Prod0,Prod) => 
  Prod=Prod0.
prod_rec([H|T], Prod0,Prod) =>
  prod_rec(T, H*Prod0,Prod).

  

You may also check:How to resolve the algorithm Arithmetic derivative step by step in the Phix programming language
You may also check:How to resolve the algorithm Loops/Infinite step by step in the Smalltalk programming language
You may also check:How to resolve the algorithm Sum to 100 step by step in the AWK programming language
You may also check:How to resolve the algorithm Roots of a quadratic function step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Gamma function step by step in the 360 Assembly programming language