|Did you know ...||Search Documentation:|
:- use_module(library(apply)).(can be autoloaded)
<=4) lists of length n head-to-tail ("fold-left"), using columns of m list elements as arguments for Goal. The
foldlfamily of predicates is defined as follows, with V0 an initial value and V the final value of the folding operation:
foldl(G, [X_11, ..., X_1n], [X_21, ..., X_2n], ..., [X_m1, ..., X_mn], V0, V) :- call(G, X_11, ..., X_m1, V0, V1), call(G, X_12, ..., X_m2, V1, V2), ... call(G, X_1n, ..., X_mn, V<n-1>, V).
No implementation for a corresponding
foldr is given. A
implementation would consist in first calling reverse/2
on each of the m input lists, then applying the appropriate
This is actually more efficient than using a properly programmed-out
recursive algorithm that cannot be tail-call optimized.
?- foldl(plus, [1,2,3], 0, N). N = 6.
Note that the last two arguments [of foldl/4-7] form a typical difference pair, so at least when the predicate is just building data structure, it is common for the last argument to be the "input" (the trivial case of the data structure) and the second-to-last argument to be the "output" (the complete data structure).
(From "An Elementary Prolog Library" by Richard O'Keefe)
flip_conj(Goal, (Goal, Conj), Conj). ?- foldl(flip_conj, [p, q, r], Conj, true). Conj = (p, q, r, true).