简体   繁体   中英

Reading a user-input string in prolog

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...

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, !] .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM