bella
bella

Reputation: 123

handling input in prolog with read()

I am using read() to take in user input. I planned that my program would accept input in the form of

a,b,c,d,e

and then I would convert that into a list of the elements. But doing a test in prolog i got this

26 ?- read(X).
|: abc,def,ghi,jkl.
X = (abc, def, ghi, jkl).

I am not sure, but is this returning a structure? What can I do to convert this into a list?

Upvotes: 2

Views: 340

Answers (2)

mat
mat

Reputation: 40768

(abc, def, ghi, jkl) is a term with functor ',' and arity 2. You can use term inspection predicates like (=..)/2, functor/3, arg/3 etc. to decompose it, or try write_canonical/1:

?- T = (abc, def, ghi, jkl), write_canonical(T).
','(abc,','(def,','(ghi,jkl)))
T = (abc, def, ghi, jkl).

To convert such tuples to lists, you can use a DCG:

tuple_list((A,B)) --> !, tuple_list(A), tuple_list(B).
tuple_list(A)     --> [A].

Example:

?- T = (abc, def, ghi, jkl), phrase(tuple_list(T), Ls).
T = (abc, def, ghi, jkl),
Ls = [abc, def, ghi, jkl].

Upvotes: 5

Sebi
Sebi

Reputation: 4522

X = (abc, def, ghi, jkl).

That is a set of symbols; prolog doesn't recognize non-types(int,long,double,...).

A list is represented by a head(first element) and a tail(the remaining elements). Try running the following examples:

   ?- [1,2,3,4,5,6]=[Head|Tail].
   ?- [1,2,3,4,5,6]=[First,Second|Tail].

Now you need to get familiarized with recursion(it is the heart of prologue). An insertion procedure might look like:

   insert(X, List, [X|List]).

But what if the list is empty; our procedure thinks that list is not so we need another procedure to suffice the previous:

   insert(X, [], [X|]).

We can do more: for instance check if an item is present within a list:

   present(Item,[Item|_]).
   present(Item,[_|Tail]) :-
     present(Item,Tail).

Notice the recursion in our last procedure: present(Item, Tail) - this recursively checks the head of the list with the variable Item which can be read from the keyboard:

   check_if_present :- read(X), present(X, List).

where List has been created at an earlier point.

We can also concatenate lists very easily:

     concatenating([],List,List).
     concatenating([Head|Tail],List,[Head|ResultedTail]) :-
      concatenating(Tail,List,ResultedTail).

Upvotes: 0

Related Questions