Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split strings in Prolog

Tags:

split

prolog

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?

like image 431
student Avatar asked Oct 16 '25 15:10

student


2 Answers

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?

like image 169
joeblog Avatar answered Oct 18 '25 13:10

joeblog


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]] ? 
like image 24
hartmut Avatar answered Oct 18 '25 12:10

hartmut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!