Reputation: 545
I want to split words from string and put into a list in Prolog.
num --> [one] | [two] | [three] | [four] | [five].
?- split("onethreetwofive", Ls).
Ls = [one,three,two,five]. % expected answer
Here, I want to split the string with matching list from num
and put the words in list. I am using SWI-Prolog. Any ideas? Thanks!
Upvotes: 1
Views: 445
Reputation: 545
Lets try this code.
:-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).
Ok Now Let's run the query.
?- split("onethreetwofive", Ls).
Ls = [one, three, two, five] ;
Upvotes: 0
Reputation: 18726
Use dcg!
:- set_prolog_flag(double_quotes, chars). num --> "one" | "two" | "three" | "four" | "five". nums --> "". nums --> num, nums.
Using 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.
OK! Next, we step up from num//0
to num//1
and from nums//0
to 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).
Let's run the query the OP suggested!
?- phrase(nums(Ls), "onethreetwofive").
Ls = [one, three, two, five] ;
false.
Upvotes: 4