Prolog getting head and tail of string

后端 未结 3 1410
情话喂你
情话喂你 2020-12-11 03:47

I\'m trying to wrap my brain around Prolog for the first time (SWI-Prolog) and I\'m struggling with what I\'m sure are the basics. I\'m trying to take a string such as \"pie

3条回答
  •  被撕碎了的回忆
    2020-12-11 04:27

    The problems with your code are:

    spellWord(String) :- String = [H|T], writeChar(H), spellWord(T).
    

    When you give this predicate a long string, it will invoke itself with the tail of that string. But when String is empty, it cannot be split into [H|T], therefore the predicate fails, returning false.

    To fix this, you have to define additionally:

    spellWord([]).
    

    This is the short form of:

    spellWord(String) :- String = [].
    

    Your other predicate also has a problem:

    writeChar(String) :- H == "P", print4("Papa").
    

    You have two variables here, String and H. These variables are in no way related. So no matter what you pass as a parameter, it will not influence the H that you use for comparison. And since the == operator only does a comparison, without unification, writeChar fails at this point, returning false. This is the reason why there is no output at all.

提交回复
热议问题