Reputation: 168
I am beginner in Prolog. I am using swi prolog(just started using it) and I need to split a user input string into a list. I tried the following code, but I get an error stating that 'Full stop in clause-body?Cannot redefine ,/2'
write('Enter the String'),nl,read('I').
tokenize("",[]).
tokenize(I,[H|T]):-fronttoken(I,H,X),tokenize(X,T).
Can someone help me with this pls...
Upvotes: 4
Views: 9271
Reputation: 60034
From your error message, it's apparent you're using SWI-Prolog. Then you can use its library support:
?- read_line_to_codes(user_input,Cs), atom_codes(A, Cs), atomic_list_concat(L, ' ', A).
|: hello world !
Cs = [104, 101, 108, 108, 111, 32, 119, 111, 114|...],
A = 'hello world !',
L = [hello, world, !].
To work more directly on 'strings' (really, a string is a list of codes), I've built my splitter, with help from string//1
:- use_module(library(dcg/basics)).
%% splitter(+Sep, -Chunks)
%
% split input on Sep: minimal implementation
%
splitter(Sep, [Chunk|R]) -->
string(Chunk),
( Sep -> !, splitter(Sep, R)
; [], {R = []}
).
Being a DCG, it should be called with phrase/2
?- phrase(splitter(" ", Strings), "Hello world !"), maplist(atom_codes,Atoms,Strings).
Strings = [[72, 101, 108, 108, 111], [119, 111, 114, 108, 100], [33]],
Atoms = ['Hello', world, !] .
Upvotes: 4
Reputation: 71119
Your first line is a part of some other predicate. When it is used at top-level, it is treated as a definition of a rule without head, which is invalid.
I can replicate this:
2 ?- [user].
|: write('Enter the String'),nl,read('I').
ERROR: user://1:16:
Full stop in clause-body? Cannot redefine ,/2
|:
you're missing a head in your rule, which has only body. But it must have both:
3 ?- [user].
|: tokenize("",[]).
|: tokenize(I,[H|T]) :- fronttoken(I,H,X),tokenize(X,T).
|:
this is OK.
Upvotes: 2