2013-05-03 32 views
3

我是Prolog的初学者。我正在使用swi prolog(刚开始使用它),我需要将用户输入字符串分割成一个列表。我想下面的代码,但我得到一个错误,指出“句号条款体?不能重定义,/ 2”阅读序言中的用户输入字符串

write('Enter the String'),nl,read('I'). 
tokenize("",[]). 
tokenize(I,[H|T]):-fronttoken(I,H,X),tokenize(X,T). 

有人可以帮我这个PLS ...

+0

http://stackoverflow.com/questions/9611134/how-to-convert-a-string-read-from-被称为输入到列表中的序列号 – slackmart 2013-05-03 06:43:55

回答

3

从您的错误消息中,很明显你正在使用SWI-Prolog。然后你可以使用它的库支持:

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

更直接的“弦”(实际上是一个字符串代码列表)的工作,我已经建立了我的分流,从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 = []} 
    ). 

身为DCG,它应该与短语/ 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, !] . 
+0

谢谢f或帮助! – User111213 2013-05-04 23:18:49

1

你的第一个行是其他谓词的一部分。当它在顶层使用时,它被视为无头的规则的定义,这是无效的。

我可以复制这样的:

2 ?- [user]. 
|: write('Enter the String'),nl,read('I'). 
ERROR: user://1:16: 
     Full stop in clause-body? Cannot redefine ,/2 
|: 

你在你的规则,它只有身体缺少了头。但它必须同时具有以下两种情况:

3 ?- [user]. 
|: tokenize("",[]). 
|: tokenize(I,[H|T]) :- fronttoken(I,H,X),tokenize(X,T). 
|: 

这是好的。