Your comment reminded me of my old question to myself that why foldl/4
like meta predicate does not exist for integer intervals, as foreach/2
looks like a generalized form foldl/4
.
EDIT: the semantics of forall/2
is clear , but foreach/2
is not so clear for me in spite of its familiar name. IMHO, the above two conditions are not clear for the coder.
My package pac has experimental several such mete predicates like foldl/4
. For example foldnum
. Although they are experimental and for fun, but sometime they are handy in case in a hurry for preparing debugging queries.
EDIT: A simple minded version of foreach
. I am afraid this is
too much simplified missing some important issue discussed here.
foreach(A, P, Q, X, Y):- findall(A, P, U), foldl(Q, U, X, Y).
% ?- foreach([I], between(1,10, I), pred([[J], A, B]:- B is A+J), 0, S).
%@ S = 55.
end of EDIT
% ?- show(foldnum(writeln, 1-10)).
%@ pac:pac#16(1), where
%@ pac:pac#16(A):-pac:(A>10),!
%@ pac:pac#16(A):-pac:writeln(A),pac:(B is A+1),pac:pac#16(B)
%@ true.
% ?- foldnum(writeln, 1-10).
%@ 1
%@ 2
%@ 3
%@ 4
%@ 5
%@ 6
%@ 7
%@ 8
%@ 9
%@ 10
%@ true.
% ?- F = plus, foldnum(F, 1-100, 0, R).
%@ F = plus,
%@ R = 5050.
% ?- N=100, functor(A, #, N),
% forall(between(1, N, I), nb_setarg(I, A, I)),
% foldnum(pred(A, ([J, C, D]:- arg(J, A, Aj), D is C * Aj) ),
% 1 - N, 1, S).
%@ N = 100,
%@ A = #(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100),
%@ S = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000.
For curiosity and testing, I added my version foreach
to my pac library. I think discussions in this thread are much more deep than I could understand currently. So I do not insist at all my first intuition.
EDIT:
% ?- alaforeach(I, between(1, 10, I), pred([J, A, B]:- B is A+J), 0, S).
%@ S = 55.
etc(alaforeach, [A, F, G|Args], M, meta:H, P, Q):- (var(F); var(G)), !,
expand_arg(F, M, F0, P, P0),
expand_arg(G, M, G0, P0, Q),
complete_args(foreach(A, F0, G0), Args, H).
etc(alaforeach, [A, F, G|Args], M, H, P, Q):-!,
expand_arg(F, M, F0, P, P0),
expand_etc(foldl(G, U), M, G0, P0, Q),
complete_args(G0, Args, G1),
H = ( findall(A, F0, U), G1 ).