SørenHN
SørenHN

Reputation: 696

How to read list of atoms?

I would like to read in a list of atoms from the user the program.

Right now, I do it recursively and in each iteration check whether the in-putted atom is not x.

getAtomList([H | T]):-
    write('> '),
    read_atom(Input),
    (Input \= x -> 
        H = Input, getAtomList(T);
        H = [], T = []).

But running this, does not create the list as i would like it. Instead it does this:

> a
> b
> c
> x
[a,b,c,[]]

And I would expect the constructed list to be [a,b,c].

How do I read in a list of atoms recursively? Or, alternatively, is there another (easier) way to do this?

Upvotes: 0

Views: 83

Answers (1)

CapelliC
CapelliC

Reputation: 60014

should be

getAtomList(L):-
    write('> '),
    read_atom(Input),
    (Input \= x -> 
        L = [Input|T], getAtomList(T);
        L = []).

but I don't have read_atom/1 available, so this goes untested...

edit

anyway, seems correct. Replacing read_atom/1 by read_string/2 I get

...
    read_line_to_string(user_input,Input),
    (Input \= "x" ->
...

?- getAtomList(L).
> a
> b
> c
> x
L = ["a", "b", "c"].

So let's define read_atom/1 like

read_atom(A) :-
    read_line_to_string(user_input,S),
    atom_string(A,S).

Now should be ok.

Upvotes: 2

Related Questions