Search code examples
prolog

Prolog convert list of string to list of numbers


I'm new at Prolog and want to convert a list of string numbers to a list of numbers. I would appreciate an explanation, as I'm struggling with list operations in this language.

Here is what I've got so far (recursively):

convert([], 0). # This is meant to be the simplest case, if there are no elements left in the list.
convert([H|T], L) :- # This is meant to be executed if there are elements in the list.
   string_to_atom(H, Elm), # Built in function from [here][1].
   convert([T|_],L1). # The recursive call to the tail T. Unsure about how to call this.

Thanks in advance!

Edit: link to string_to_atom function: https://www.swi-prolog.org/pldoc/man?predicate=string_to_atom/2


Solution

  • You were nearly there! Note that the character for comments is %, not #

    convert(Xs, Ys) is the predicate establishing a relation between Xs and Ys, such that when there are elements in Xs, then the head element H is relation with Elm, where string_to_atom(H, Elm). So Elm is the atom equivalent of H.

    convert([], []). % there are no elements in list Xs
    convert([H|Ts], [Elm|Es]) :- % This is meant to be executed if there are elements in the list.
       string_to_atom(H, Elm), % Built in function from [here][1].
       convert(Ts, Es). % The recursive call to the tail T
    

    You should read carefully the explanations for standard predicates like append/2. They give you the proper way to reason with relations.