Skip to main content David Edelstein's Blog

🦙
🦙

foldl in prolog (2)

Published: 2011-06-14
dave@edelsteinautomotive.com
David Edelstein

Here’s another shot of foldl in prolog. this one is a little cleaner than the last version.

foldl(Gen, Pred, In=Init, Out) :-
    H=hold(Init),
    (   Gen,
        H=hold(CurVal),
        In=CurVal,
        Pred,
        nb_setarg(1, H, Out),
        fail
    ;   H=hold(Out)
    ).</pre>

here are the same samples provided before

?- foldl(member(Loc, [1,5,9]), append(In,[Loc,space],Out),
        In=[], Out).
Out = [1, space, 5, space, 9, space].

?- foldl(range(1,3,L), Out is In+L, In=0, Out).
Out = 6.