views:

86

answers:

1

Hello hello :D :D I'm working on this this wonderful Prolog project and I'm stuck at this situation where I need to translate certain words into other words (e.g "i" into "you". "my into "your")

This is what I've done and I'm pretty sure it's kidna iffy. I enter the sentence and when It goes to convert it only changes the one word then goes on wacky on me. (e.g. "i feel happy" changes to "you" then it crashes.) Any suggestions?

translate([]).
translate([H|T], [NewH|NewT]):-
             means(H,NewH);
             spit(T,NewT).
means(i,you).
means(my,your).
means(mine,yours).
+2  A: 

Here's the fix:

translate([], []).
translate([H|T], [NewH|NewT]):-
             means(H, NewH),
             translate(T,NewT).
means(i, you) :- !.
means(my, your) :- !.
means(mine, yours) :- !.
means(X, X).

The changes are as follows:

  1. I fixed the missing parameter to the first definition of translate (it's considered a completely independent function if the number of parameters don't match).
  2. I'm calling translate on the rest of the list when the first item is translated.
  3. I'm asserting that every word means itself unless specified otherwise. The :- ! part means if you match this, don't try the rest (this is to avoid lists always matching with themselves).

Example usage:

?- translate([this, is, i], X).
X = [this, is, you].
Max Shawabkeh
With SWI-Prolog's `maplist/N` you can just write `?- maplist(means, [this, is, i], X).X = [this, is, you].`, i.e. no need to define `translate/2`.
Kaarel
Thanks, that worked perfectly :D
Sally Walker
@Kaarel, the question is tagged with "beginner" so I figured it's better to show it step-by-step.
Max Shawabkeh