peter9464
peter9464

Reputation: 57

My Prolog "translator" script returns an empty list

I am trying to write a simple translator, where you enter a list of numerical numbers and it returns their string values like so :

translate([1,2,3], X). X=[one, two, three].

The code I have written works...except it returns an empty list. Here is my code and the trace:

means(1, one).
means(2, two).
means(3, three).
means(4, four).
means(5, five).
means(6, six).
means(7, seven).
means(8, eight).
means(9, nine).
means(10, ten).

translate([], X).
translate([H|T], []):-
    means(H, X),
translate(T, X).

translate([H|T], X):-
    means(H, Y),
    translate(T, [X|Y]).


[trace] 1 ?- translate([1,2,3], X).
    Call: (6) translate([1, 2, 3], _G2219) ? creep
    Call: (7) means(1, _G2301) ? creep
    Exit: (7) means(1, one) ? creep
    Call: (7) translate([2, 3], one) ? creep
    Call: (8) means(2, _G2301) ? creep
    Exit: (8) means(2, two) ? creep
    Call: (8) translate([3], [one|two]) ? creep
    Call: (9) means(3, _G2304) ? creep
    Exit: (9) means(3, three) ? creep
    Call: (9) translate([], [[one|two]|three]) ? creep
    Exit: (9) translate([], [[one|two]|three]) ? creep
    Exit: (8) translate([3], [one|two]) ? creep
    Exit: (7) translate([2, 3], one) ? creep
    Exit: (6) translate([1, 2, 3], []) ? creep
X = [] .

My other question is: why is my list concatenating as [[one|two]|three]? instead of [one, two, three]?

Thanks,

Upvotes: 1

Views: 507

Answers (2)

Daniel Lyons
Daniel Lyons

Reputation: 22803

Doing it manually Sergey's way is good practice, but you can simplify even further with maplist/3:

translate(Numbers, Words) :- maplist(means, Numbers, Words).

Upvotes: 1

Sergii Dymchenko
Sergii Dymchenko

Reputation: 7209

You get empty list because of translate([H|T], []) clause.

The whole program (except means facts) can be just this simple:

translate([], []).

translate([NumH | NumT], [WordH | WordT]) :-
    means(NumH, WordH),
    translate(NumT, WordT).

Upvotes: 3

Related Questions