1
votes

I am trying to create a predicate in Prolog that applies another predicate to all elements in a given list:

take_items(_,[],_).
take_items(Stock,[Item|BTail],_) :-
    take_item(Stock,Item,Updates),
    take_items(Updates,BTail,Updates).

FYI: I am using SWI-Prolog. When in trace mode I can see that it indeed does what I want it to, but then starts backtracking. Here is the trace output from where it hits the base case to end:

   Call: (8) take_items([item(a, 2), item(b, 1)], [], [item(a, 2), item(b, 1)]) ? creep
   Exit: (8) take_items([item(a, 2), item(b, 1)], [], [item(a, 2), item(b, 1)]) ? creep
   Exit: (7) take_items([item(a, 2), item(b, 3)], [item(b, 2)], [item(a, 2), item(b, 3)]) ? creep
   Exit: (6) take_items([item(a, 3), item(b, 3)], [item(a, 1), item(b, 2)], _G1991) ? creep
true .

How do I get it to output X = [list, of, items] when callingtake_items([first,list],[second,list],X).?

1
What's the point of the third parameter, if both clauses ignore it? - Sergey Kalinichenko
Please forgive me if this seems very silly. I am new to Prolog. The third parameter is where the wanted result is dumped. - user3037928

1 Answers

0
votes

this should work

take_items(_,[],[]).
take_items(Stock,[Item|BTail],[Update|Updates]) :-
    take_item(Stock,Item,Update),
    take_items(Updates,BTail,Updates).

I am trying to create a predicate in Prolog that applies another predicate to all elements in a given list:

actually, there is maplist/3 available

take_items(Stock,Items,Updates) :- maplist(take_item(Stock),Items,Updates).