Prolog - listing output?

I have a function

sublist(_,[_],_) :-
    !.
sublist(X,[Y|T],Z) :-
    R is X - Y,
    sublist(X,T,[R|Z]).

      

call example sublist(2,[1,2,3],Z)

. At the end of the execution, he just gives me a yes, but I would like to see the contents of Z.

I know this is somehow simple, since I have other instructions that do similar things, but this one does not work.

0


source to share


2 answers


I am also assuming that sublist / 3 should subtract a number from all the elements in the list.

The reason you don't get any result for Z is because you are building a list on the way to recursion. This means that when the stop predicate succeeds, Prolog returns it back from recursion and Z becomes untested again.

Z is ?
    |
    Z is [-1]
        |
        Z is [-1, 0]
            |
            Z is [-1, 0, 1]
            |
        Z is [-1, 0]
        |
    Z is [-1]
    |
Z is ?

      

Try to get into recursion first and build your list in the output. Maybe like this:



subtract_list(_, [], []).

subtract_list(Number, [Head|Tail], [Subtracted|Result]):-
    subtract_list(Number, Tail, Result),
    Subtracted is Head - Number.

      

All we changed is the order of the rules in the recursive predicate and the conditions for the stop condition. Now it repeats until it reaches an empty list, after which it also instantiates a result variable with an empty list. Then it bubbles up adding values ​​to the list as it does.

?- subtract_list(1,[4,3,2],Z).
Z = [3, 2, 1] 

      

Hope this helps. Tom

+3


source


You are not really specifying what you should do sublist/3

, but perhaps you mean this:

sublist(_, [], []) :- !.

sublist(X, [Y | T], [R | Z]) :-
    R is X - Y,
    sublist(X, T, Z).

      

Usage example:

?- sublist(2, [1, 2, 3], Z).
Z = [1, 0, -1].

      



Btw if you don't want to iterate over the list yourself, then you can use maplist/3

that provided by SWI-Prolog. First, define your desired calculation:

my_calculation(X, Y, Z) :-
    Z is X - Y.

      

and then call maplist/3

:

?- maplist(my_calculation(2), [1, 2, 3], Z).
Z = [1, 0, -1].

      

+1


source







All Articles