performance - 使用字符列表进行模式匹配
问题描述
我在模式匹配转换为字符列表的单词时遇到困难:
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
,但有了它,我得到一个超时错误。任何人都可以为我建议一种更好的方法来构建我的代码吗?
解决方案
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
。
推荐阅读
- react-native - Unable to play two videos side by side in separate containers, how can I fix this? When I comment out one video, the other appears and plays
- delphi - CBuilder TMenu showing in wrong place
- python - Generate a random gaussian signal of 5000 samples
- installation - 从 packages.config 迁移到 PackageReference 后 VS2019 MSI 安装程序错误 2727
- excel - 从公共功能更改为子功能
- azure - 将 Kafka 连接到 SCADA 系统
- java - 将属性分配给文本文件中的字符串
- python - 如何在python中将igraph结果导出为csv文件?
- pandas - Pandas 将年/月 Int 列转换为日期时间和季度平均值
- javascript - 将属性转换为 javascript 对象(错误字符结果)