那些双引号字符串实际上是字符代码的列表。那么 DCG 是处理解析的适当方式:
:- use_module(library(http/dcg_basics), [string//1]).
%% split input on Sep
splitter(Sep, [Chunk|R]) -->
string(Chunk),
( Sep -> !, splitter(Sep, R)
; [], {R = []}
).
Sep 以上可以是文字,也可以是非终结符。我们需要类似的东西
not_in_word --> [C], {\+code_type(C, alpha)}.
有这样的定义:
?- phrase(splitter(not_in_word, X), "stack,overflow!rocks.").
X = [[115, 116, 97, 99, 107], [111, 118, 101, 114, 102, 108, 111|...], [114, 111, 99, 107, 115], []] .
我们可以使用 delete/3 删除空字符串:
?- phrase(splitter(not_in_word, X), "? stack,overflow!rocks."), delete(X, [], Y).
X = [[], [], [115, 116, 97, 99, 107], [111, 118, 101, 114, 102|...], [114, 111, 99, 107|...], []],
Y = [[115, 116, 97, 99, 107], [111, 118, 101, 114, 102, 108, 111|...], [114, 111, 99, 107, 115]] .
edit我们可以很容易地将单词想象成原子:
?- phrase(splitter(not_in_word, X), "? stack,overflow!rocks."),
delete(X, [], Y),
maplist(atom_codes, Z, Y).
X = [[], [], [115, 116, 97, 99, 107], [111, 118, 101, 114, 102|...], [114, 111, 99, 107|...], []],
Y = [[115, 116, 97, 99, 107], [111, 118, 101, 114, 102, 108, 111|...], [114, 111, 99, 107, 115]],
Z = [stack, overflow, rocks] .
注意 maplist(atom_codes, Atoms, Codes) 中“输出”单词的位置...