Search code examples
prolog

SWI-Prolog Parsing input without querying


I have some simple code here:

main:-
    read_string(user_input,"\n","\r\t",_,S),
    split_string(S," ", "", Ls),
    ask(Ls).

ask([First, Second|O]) :-
    First = who,
    Second = sells,
    write(O).

The problem is when you type this:

?- main.
|:who sells fries
false.

?- ask([who, sells, fries]).
[fries]
true.

I want the 1st option to work like the second and I can't understand why it doesn't work. Shouldn't the "who sells fries" being queried through main be the same as just querying "ask" myself?

Am I missing some fundamental issue with functional programming (which I admit i'm really struggling with)?


Solution

  • Prolog is capable of processing strings, one character at a time. But people prefer to read strings as words. So Prolog has different ways of expressing strings, depending on the flag double_quotes.

    I suggest that you read up the basic data types in Prolog.

    The first query main/0 fails because the string that is read: who sells fries and split into the list of sub strings: who, sells, fries, will not unify with the list of atoms who, sells, fries in the ask/1 predicate. To make this query succeed, rewrite:

    ask([First, Second|O]) :-
        First = "who",    % check for the string "who"
        Second = "sells", % check for the string "sells"
        write(O).
    

    The second query provides ask/1 with a list of atoms, which will unify with the atoms within ask/1.