从 Prolog 中的字符串拆分单词

Split words from string in Prolog

我想从字符串中拆分单词并放入 Prolog 中的列表。

num --> [one] | [two] | [three] | [four] | [five].

?- split("onethreetwofive", Ls).
Ls = [one,three,two,five].             % expected answer

在这里,我想从 num 中拆分带有匹配列表的字符串并将单词放入列表中。我正在使用 SWI-Prolog。有任何想法吗?谢谢!

使用!

:- set_prolog_flag(double_quotes, chars).

num --> "one" | "two" | "three" | "four" | "five".

nums --> "".
nums --> num, nums.

使用 SWI-Prolog 7.3.15:

?- phrase(nums, Cs).
Cs = [] ;
Cs = [o, n, e] ;
Cs = [o, n, e, o, n, e] ;
Cs = [o, n, e, o, n, e, o, n, e] ;
...

?- phrase(nums, "onethreetwofive").
true ;
false.

好的!接下来,我们从 num//0 上升到 num//1,从 nums//0 上升到 nums//1

num(one)   --> "one".
num(two)   --> "two".
num(three) --> "three".
num(four)  --> "four".
num(five)  --> "five".

nums([])     --> "".
nums([X|Xs]) --> num(X), nums(Xs).

让我们运行 OP 建议的查询!

?- phrase(nums(Ls), "onethreetwofive").
Ls = [one, three, two, five] ;
false.

让我们试试这个代码。
:-set_prolog_flag(double_quotes, codes).
any(A,K) --> {member(S,K)}, S, {atom_codes(A, S)}.
num(S) --> any(S, ["one","two","three","four","five"]).
nums([]) --> "".
nums([X|Xs]) --> num(X), nums(Xs).

split(Str,Ls):-phrase(nums(Ls),Str).

好的,现在让我们 运行 查询。
?- split("onethreetwofive", Ls).
Ls = [one, three, two, five] ;