Skip to main content
Version: Next

foldl/6

Module

This predicate is provided by apply.pl.

Load this module before using the predicate:

:- consult('/v1/lib/apply.pl').

Description

Left-folds three lists in lockstep using Goal. Goal is called as call(Goal, Elem1, Elem2, Elem3, Acc0, Acc1).

Signature

foldl(:Goal, +List1, +List2, +List3, +V0, -V) is det

Examples

Fold three lists in lockstep to compute weighted sum

This scenario demonstrates how to use foldl/6 to fold three lists simultaneously.

Here are the steps of the scenario:

  • Given the program:
weighted_sum(X, Y, Z, Acc0, Acc) :- Acc is Acc0 + (X * Y * Z).
  • Given the query:
consult('/v1/lib/apply.pl'),
foldl(weighted_sum, [1,2], [3,4], [5,6], 0, Result).
  • When the query is run
  • Then the answer we get is:
height: 42
gas_used: 4307
answer:
has_more: false
variables: ["Result"]
results:
- substitutions:
- variable: Result
expression: 63

Fold three empty lists returns the initial accumulator

Here are the steps of the scenario:

  • Given the program:
weighted_sum(X, Y, Z, Acc0, Acc) :- Acc is Acc0 + (X * Y * Z).
  • Given the query:
consult('/v1/lib/apply.pl'),
foldl(weighted_sum, [], [], [], 42, Result).
  • When the query is run
  • Then the answer we get is:
height: 42
gas_used: 4062
answer:
has_more: false
variables: ["Result"]
results:
- substitutions:
- variable: Result
expression: 42

Fold three lists to build a structured result

Here are the steps of the scenario:

  • Given the program:
make_triple(X, Y, Z, Acc0, [[X,Y,Z]|Acc0]).
  • Given the query:
consult('/v1/lib/apply.pl'),
foldl(make_triple, [a,b], [1,2], [x,y], [], Triples).
  • When the query is run
  • Then the answer we get is:
height: 42
gas_used: 4283
answer:
has_more: false
variables: ["Triples"]
results:
- substitutions:
- variable: Triples
expression: "[[b,2,y],[a,1,x]]"