Sally Walker
Sally Walker

Reputation: 47

Translate Prolog Words

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 kinda 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.)

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

Upvotes: 2

Views: 3930

Answers (1)

Max Shawabkeh
Max Shawabkeh

Reputation: 38663

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].

Upvotes: 2

Related Questions