Search code examples
performanceprologcallpredicateevaluation

Pattern matching using list of characters


I am having difficulty pattern matching words which are converted to lists of characters:

wordworm(H1,H2,H3,V1,V2) :-
    word(H1), string_length(H1,7), 
    word(H2), string_length(H2,5),
    word(H3), string_length(H3,4),
    word(V1), string_length(V1,4), 
       word(H3) \= word(V1),
       atom_chars(H2, [_,_,Y,_,_]) = atom_chars(V1, [_,_,_,Y]),
    word(V2), string_length(V2,5), 
       word(H2) \= word(V2),
       atom_chars(H3, [_,_,_,Y]) = atom_chars(V2, [_,_,_,_,Y]).

Above this section, I have a series of 600 words in the format, word("prolog"). The code runs fine, without the atom_chars, but with it, I get a time-out error. Can anyone suggest a better way for me to structure my code?


Solution

  • Prolog predicate calls are not like function calls in other languages. They do not have "return values".

    When you write X = atom_chars(foo, Chars) this does not execute atom_chars. It builds a data structure atom_chars(foo, Chars). It does not "call" this data structure.

    If you want to evaluate atom_chars on some atom H2 and then say something about the resulting list, call it like:

    atom_chars(H2, H2Chars),
    H2Chars = [_,_,Y,_,_]
    

    So overall maybe your code should look more like this:

    ...,
    atom_chars(H2, H2Chars),
    H2Chars = [_,_,Y,_,_],
    atom_chars(V1, V1Chars),
    V1Chars = [_,_,_,Y],
    ...
    

    Note that you don't need to assert some kind of "equality" between these atom_chars goals. The fact that their char lists share the same variable Y means that there will be a connection: The third character of H2 must be equal to the fourth character of V1.