search in a split a sentence in prolog

95 Views Asked by At

I have a list L created as:

atomic_list_concat(L,' ', 'This is a string').

L = ['This',is,a,string]

Now I want to search an atom in L using member function. I tried :

?- member(' is',L).
L = [' is'|_G268] .

?- member( is,L).
L = [is|_G268] .

What is it that I am doing wrong here?

2

There are 2 best solutions below

0
On BEST ANSWER

Although the solution posted by dasblinkenlight is correct, it somewhat breaks the interactive nature of using the Prolog top-level. Typically, you want to base your next query on the previous solution.

For this reason it is possible to reuse top-level bindings by writing $Var where Var is the name of a variable used in a previous query.

In your case:

?- atomic_list_concat(L, ' ', 'This is a string').
L = ['This', is, a, string].
?- member(' is', $L).
false.
?- member('is', $L).
true ;
false.

PS: Notice that you would not get a result when searching for ' is' since separators are removed by atomic_list_concat/3.

2
On

Prolog predicates that you run interactively do not carry the state. When you run

atomic_list_concat(L,' ', 'This is a string').

the interpreter shows you an assignment for L, and then forgets its value. When you run member/2 on the next line, L is back to its free variable state.

If you want the same L to carry over, you need to stay within the same request, like this:

:- atomic_list_concat(L,' ', 'This is a string'),
   member(is, L),
   writeln('membership is confirmed').

Now L assignment from atomic_list_concat is available to member/2, letting it check the membership.