首页 > 解决方案 > 使用字符列表进行模式匹配

问题描述

我在模式匹配转换为字符列表的单词时遇到困难:

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]).

在本节上方,我有一系列 600 字的格式,word("prolog"). 代码运行良好,没有atom_chars,但有了它,我得到一个超时错误。任何人都可以为我建议一种更好的方法来构建我的代码吗?

标签: performanceprologcallpredicateevaluation

解决方案


Prolog 谓词调用与其他语言中的函数调用不同它们没有“返回值”。

当你写X = atom_chars(foo, Chars)不会执行atom_chars。它构建了一个数据结构 atom_chars(foo, Chars)。它不会“调用”这个数据结构。

如果你想atom_chars对某个原子进行评估H2,然后对结果列表说些什么,可以这样称呼它:

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

所以总的来说,你的代码应该看起来更像这样:

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

请注意,您不需要在这些atom_chars目标之间断言某种“平等”。他们的 char 列表共享同一个变量这一事实Y意味着会有一个连接: 的第三个字符H2必须等于 的第四个字符V1


推荐阅读