I am trying to write a Prolog program such that given a list of numbers like [1, 2, 3]
, it will convert them into a list of words representing those numbers ['one', 'two', 'three']
.
My code so far:
totext(0, 'zero').
totext(1, 'one').
totext(2, 'two').
totext(3, 'three').
totext(4, 'four').
totext(5, 'five').
totext(6, 'six').
totext(7, 'seven').
totext(8, 'eight').
totext(9, 'nine').
translate([], []).
translate([Head|Rest], [TranslatedHead|TranslatedRest]) :-
totext(Head, TranslatedHead),
translate(Rest, TranslatedRest).
When I load up gprolog
and consult the file, if I do:
translate([], X).
I correctly get:
X = []
yes
But when I do
translate([1,2], X).
I get:
uncaught exception: error(existence_error(procedure,totext/0),translate/0)
I am very new to Prolog (this is my first Prolog program), and I have no idea what is going wrong here. Any ideas? Thanks.
gprolog
and dotranslate([1,2], X).
I getX = [one, two]
. I'll bet you put a space aftertranslate
. Note thetranslate/0
in the error, meaning "no arguments" fortranslate
. Did you typetranslate ([1,,2], X).
? That won't work. An aside, you can usemaplist
for this kind of list processing:maplist(totext, Numbers, Names)
. Trymaplist(totext, [1,2,3], Names)
.