Reading a user-input string in prolog

人盡茶涼 提交于 2020-01-04 02:49:05

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/16353000/reading-a-user-input-string-in-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!