I am trying to understand how user enter a sentence then will split in Prolog into separate words. For example, user enters this sentence: "computer consists of hardware" I want to divide this sentence to: "computer", "consists", "of" and "hardware"
Can someone please explain how user enters sentence then split it in Prolog?
Swi-Prolog has a built-in predicate which makes this fairly easy:
?- split_string("computer consists of hardware", "\s", "\s", L).
L = ["computer", "consists", "of", "hardware"].
As far as I understand the third argument, +PadChars, in split_string(+String, +SepChars, +PadChars, -SubStrings)
, it trims surrounding spaces.
For example, adding leading and trailing spaces in this example with +PadChars set to an empty string produces:
?- split_string(" computer consists of hardware ", "\s", "", L).
L = ["", "computer", "consists", "of", "hardware", ""].
Whereas setting PadChars to "\s" produces:
?- split_string(" computer consists of hardware ", "\s", "\s", L).
L = ["computer", "consists", "of", "hardware"].
But I'm not entirely clear if +PadChars serves any other purpose. Anyone know of any good examples to clarify it?
If the sentence is contained in a list (i.e., [computer, consists, of, hardware]) then you could use:
split(L,Result) :-
splitacc(L, [], Result).
splitacc([], Acc, Result) :-
Result=Acc.
splitacc([H|T], Acc, Result) :-
append(Acc, [[H]], NewAcc),
splitacc(T, NewAcc, Result).
For instance:
?- split([a, computer, consists, hardware],L).
L = [[a],[computer],[consists],[hardware]] ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With