对于你的第一个解决方案,问题是虽然你建立了正确的列表,但你在每个步骤中传递一个匿名变量'_',它与任何事物相统一,而不是你想要返回的列表变量的名字结束。
我试图构建解决方案谓词is_alpha的/ 1代替字母,因为你的避风港;吨给出的代码,但它应该是相同的....有一些变化代码:
splitintowords(CharList, WordList):- splitintowords_(CharList, [], [], WordList).
splitintowords_([],[], Res, Res).
splitintowords_([],Word, WordList,L):-
\+ Word = [],
append([Word], WordList, NWordList),
splitintowords_([],[], NWordList,L).
splitintowords_([H|T],Word, WordList,L):-
is_alpha(H),
append([H], Word, NWord),
splitintowords_(T,NWord, WordList,L).
splitintowords_([H|T],Word, WordList,L):-
\+ is_alpha(H),
append([Word], WordList, NWordList),
splitintowords_(T, [], NWordList,L).
例如:
string_codes('hello there, how are you?',T), splitintowords(T, W).
T = [104, 101, 108, 108, 111, 32, 116, 104, 101|...],
W = [[117, 111, 121], [101, 114, 97], [119, 111, 104], [], [101, 114, 101, 104|...], [111, 108, 108|...]] ;
false.
注意,因为该解决方案是非常大的它显示...,你可以通过按w
看到完整的解决方案SWI-序言:
?- string_codes('hello there, how are you?',T), splitintowords(T, W).
T = [104, 101, 108, 108, 111, 32, 116, 104, 101|...],
W = [[117, 111, 121], [101, 114, 97], [119, 111, 104], [], [101, 114, 101, 104|...], [111, 108, 108|...]] [write]
T = [104, 101, 108, 108, 111, 32, 116, 104, 101, 114, 101, 44, 32, 104, 111, 119, 32, 97, 114, 101, 32, 121, 111, 117, 63],
W = [[117, 111, 121], [101, 114, 97], [119, 111, 104], [], [101, 114, 101, 104, 116], [111, 108, 108, 101, 104]] ;
false.
(第二个T,W是第一个T,W的完整解)。
而且你第二个解决方案的一些类似的变化:
splitintowords(CharList, WordList):-
splitintowords_(CharList, [[]], WordList).
splitintowords_([], WordList, WordList).
splitintowords_([H|T], [Word|Words], L):-
is_alpha(H),
WordN = [H|Word],
splitintowords_(T, [WordN|Words], L).
splitintowords_([H|T], Words,L):-
\+ is_alpha(H),
WordsN = [[]|Words],
splitintowords_(T, WordsN,L).
例子:
?- string_codes('hello there, how are you?',T), splitintowords(T, W).
T = [104, 101, 108, 108, 111, 32, 116, 104, 101, 114, 101, 44, 32, 104, 111, 119, 32, 97, 114, 101, 32, 121, 111, 117, 63],
W = [[], [117, 111, 121], [101, 114, 97], [119, 111, 104], [], [101, 114, 101, 104, 116], [111, 108, 108, 101, 104]] ;
false.
需要注意的是在中间某个地方有一个空表比以前的解决方案的更多。如果你想摆脱空列表,这将是写一个更断言非常简单:
delete([],[]).
delete([H|T],[H|T1]):-dif(H,[]),delete(T,T1).
delete([[]|T],T1):-delete(T,T1).
例子:
?- delete([[], [117, 111, 121], [101, 114, 97], [119, 111, 104], [], [101, 114, 101, 104, 116], [111, 108, 108, 101, 104]],L).
L = [[117, 111, 121], [101, 114, 97], [119, 111, 104], [101, 114, 101, 104, 116], [111, 108, 108, 101, 104]] ;
false.
(它可以除去空列表)。
编辑
我也与你的谓语alphabetic/1
进行了测试,并产生完全相同的输出与is_alpha/1
。
请提供谓词字母/ 1。 – coder
字母(N): - char_type(N,alpha)。 – ejbs
这个例子中的词是什么? “你好,那里,你怎么样,你呢?” –