projog

3.107. foldl(PredicateName, Values, Start, Result) - combines elements of a list into a single term.

See Wikipedia.

Examples

multiple_result_predicate(X,Y,Z) :-  Z is X+Y.
multiple_result_predicate(X,Y,Z) :-  Z is X*Y.

single_result_predicate(X,Y,Z) :-  Z is X+Y.

?- foldl(single_result_predicate, [2,4,7], 0, X).
X = 13

yes

?- foldl(single_result_predicate, [2,4,7], 42, X).
X = 55

yes

?- foldl(single_result_predicate, [2,4,7], 0, 13).

yes

?- foldl(single_result_predicate, [2,4,7], 0, 12).

no

?- foldl(single_result_predicate, [], 7, X).
X = 7

yes

?- foldl(single_result_predicate, [3], 7, X).
X = 10

yes

?- foldl(multiple_result_predicate, [2,4,7], 42, X).
X = 55

yes;
X = 336

yes;
X = 183

yes;
X = 1232

yes;
X = 95

yes;
X = 616

yes;
X = 343

yes;
X = 2352

yes

?- foldl(multiple_result_predicate, [1,2,3], 0, X).
X = 6

yes;
X = 9

yes;
X = 5

yes;
X = 6

yes;
X = 5

yes;
X = 6

yes;
X = 3

yes;
X = 0

yes

?- foldl(multiple_result_predicate, [1,2,3], 0, 6).

yes;

yes;

yes;

no

?- foldl(multiple_result_predicate, [], 7, X).
X = 7

yes

?- foldl(multiple_result_predicate, [3], 7, X).
X = 10

yes;
X = 21

yes

four_arg_predicate(1,X,Y,Z) :-  Z is X+Y.
four_arg_predicate(2,X,Y,Z) :-  Z is X-Y.
four_arg_predicate(3,X,Y,Z) :-  Z is X+Y.
four_arg_predicate(3,X,Y,Z) :-  Z is X-Y.
four_arg_predicate(a,1,2,3).
four_arg_predicate(a,x,y,3).
four_arg_predicate(a,5,3,12).
four_arg_predicate(a,999,_,99999).
four_arg_predicate(b,_,_,_).

?- foldl(four_arg_predicate(1), [2,4,7], 0, X).
X = 13

yes

?- foldl(four_arg_predicate(2), [2,4,7], 0, X).
X = 5

yes

?- foldl(four_arg_predicate(3), [2,4,7], 0, X).
X = 13

yes;
X = 1

yes;
X = 9

yes;
X = 5

yes;
X = 13

yes;
X = 1

yes;
X = 9

yes;
X = 5

yes

?- foldl(four_arg_predicate(3), [2,4,7], 0, 5).

yes;

yes

?- foldl(four_arg_predicate(a), [B,C], A, X).
A = 2
B = 1
C = 5
X = 12

yes;
A = 2
B = 1
C = 999
X = 99999

yes;
A = y
B = x
C = 5
X = 12

yes;
A = y
B = x
C = 999
X = 99999

yes;
A = 3
B = 5
C = 999
X = 99999

yes;
A = UNINSTANTIATED VARIABLE
B = 999
C = 999
X = 99999

yes

?- foldl(four_arg_predicate(3), [2,4,7], 0, 14).

no

?- foldl(four_arg_predicate(4), [2,4,7], 0, X).

no

Note: Unlike SWI Prolog, fails on first evaluation if the second argument is not a concrete list.

?- foldl(single_result_predicate, [2,4,7|T], 0, X).

Expected concrete list but got: .(2, .(4, .(7, T)))

?- foldl(single_result_predicate, L, 0, X).

Expected concrete list but got: L