tags:

views:

520

answers:

2

I have the function

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

an example call is sublist(2,[1,2,3],Z). At the end of execution it just gives me 'yes', but i'd like to see the contents of Z.

I know it's something simple as i have other instructions that do similar things, but this one isn't working.

+1  A: 

You don't really specify what sublist/3 is supposed to do but maybe 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 which is 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].
Kaarel
+2  A: 

I'm also going to assume that sublist/3 is supposed to subtract a number from all items in the list.

The reason you're not getting any result for Z is because you're building the list on the way into the recursion. Which means that when the stopping predicate succeeds, Prolog works it's way back out of the recursion and Z becomes uninstantiated 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 going into the recursion first and building your list on the way out. Maybe like this:

subtract_list(_, [], []).

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

All we've changed is the order of the rules in the recursive predicate and the terms of the stopping condition. Now it recurses until it reaches an empty list, at which point it instantiates the result variable with an empty list as well. Then it bubbles back up adding values to the list as it does so.

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

Hope this helps. Tom

Tom Wright