views:

51

answers:

1

Hi, I'm still figuring out how prolog really works and was trying to develop an small test program with an if statment but can't really get the value I need out.

prog(Sx,Sy) :- 
    Sx > 0 -> 
        update(Sx,10,S1), update(S1,10,S2), prog(S2,S2) ;
        Sy.

update(S,V,RES) :- 
    RES is S-V.

I want prog to give Sy as an answer instead of true so I can use this as an argument of another predicate. this code gives an error when the condition is false, I've tried doing:

prog([],[],Sy).
prog(Sx,Sy) :- 
    Sx > 0 -> 
        update(Sx,10,S1), update(S1,10,S2), prog(S2,S2) ;
        prog([],[],Sy).

But just returns true.

Can anybody tell me how to make it return Sy?

Thanks

+1  A: 

Prolog rules don't "Return" values, and the arrow-semicolon pattern isn't the most idiomatic way to do this. Instead you should use two rules, one for each case of Sx. I'm not sure what you're trying to represent with your example though. What value do you expect Sy to have if Sx is not greater than zero? Assuming you want Sy to be Sx in that case:

prog(Sx, Sy) :- Sx > 0, update(Sx,10,S1), update(S1,10,S2), prog(S2,Sy).
prog(Sx, Sx) :- Sx <= 0.

To use this with another predicate, you would do something like this:

prog(40, V),
write(V),
prog(V, Z),
write(Z).

And so on, with the second parameter being bound to the "answer" in each case.

hdan