How to resolve the algorithm Sum and product of an array step by step in the Prolog 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 Prolog 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 Prolog programming language

Source code in the prolog programming language

sum([],0).
sum([H|T],X) :- sum(T,Y), X is H + Y.
product([],1).
product([H|T],X) :- product(T,Y), X is H * X.

add(A,B,R):-
    R is A + B.

mul(A,B,R):-
    R is A * B.

% define fold now.
fold([], Act, Init, Init).

fold(Lst, Act, Init, Res):-
    head(Lst,Hd),
    tail(Lst,Tl),
    apply(Act,[Init, Hd, Ra]),
    fold(Tl, Act, Ra, Res).

sumproduct(Lst, Sum, Prod):-
    fold(Lst,mul,1, Prod),
    fold(Lst,add,0, Sum).

?- sumproduct([1,2,3,4],Sum,Prod).
Sum = 10,
Prod = 24 .

  

You may also check:How to resolve the algorithm Execute SNUSP step by step in the Haskell programming language
You may also check:How to resolve the algorithm Maximum triangle path sum step by step in the EasyLang programming language
You may also check:How to resolve the algorithm Closest-pair problem step by step in the Run BASIC programming language
You may also check:How to resolve the algorithm Middle three digits step by step in the Eiffel programming language
You may also check:How to resolve the algorithm Sierpinski triangle/Graphical step by step in the OCaml programming language