list - 如何在 PROLOG 中的谓词列表中查找值
问题描述
到目前为止,我已经完成了相当多的研究并尝试了不同的方法,但是即使在阅读了多个堆栈溢出答案甚至是 Addison Wesley 的 PDF 之后,我也找不到解决方法。这是代码
use_module(library(func)).
% importing library "func"
scale([c, d, e, f, g, a, b]).
scale(c, major, [c, d, e, f, g, a, b]).
scale(c, minor, [c, d, e_b, f, g, a_b, b_b]).
%1st attempt
search(note, scale):- scale(note, scale).
%2nd attempt
scaleOf(note, type_scale):- scale(note, type_scale).
on(item,[item|rest]).
on(item,[disregardHead|tail]):-
scale(tail),
on(item, tail).
%3rd attempt
fatherOf(father,type, son):- scale(father, type, sons), search(son, type, sons).
search(son, type, []):- !, fail.
search(son, type, [son|l]):- !, true.
search(son, type, [c|l]):- search(son, type, l).
我在尝试什么?很简单,可以迭代谓词标度(c,[c,d,e,f,g,a,b])。但我无法正确处理。
编辑:我有多个谓词,因为其他人建议创建一个谓词来区分一个尺度与另一个尺度。我以为我可以把它塞进任何算法,但我猜 PROLOG 不是那么宽松:p
解决方案
你可以用member/2
[swi-doc]做到这一点。这可用于搜索、与成员统一或生成列表。
所以你可以搜索:
search(Note, Scale, Item) :-
scale(Note, Scale, Items),
member(Item, Items).
重要的是Note
,Scale
和以大写Item
字母开头,因为小写的标识符是常量或函子。带有大写字母的标识符是变量。Items
因此,这将Item
与列表中的项目统一,例如,对于我们获得的给定样本数据:
?- search(c, minor, Item).
Item = c ;
Item = d ;
Item = e_b ;
Item = f ;
Item = g ;
Item = a_b ;
Item = b_b.
推荐阅读
- javascript - 如何解析从后端接收到的错误并在 javascript 中作为 Error 对象分派
- php - Laravel - 如何存储来自动态表单字段的数据?
- stm32 - 在 STM32L100Rc 上退出 STOP 模式
- django - django-rest-framework 自动生成 html id / css
- mysql - DeprecationWarning:布尔值已传递给 options.operatorsAliases。这是 v5 的无操作,应删除
- c# - TPL DataFlow 处理异常的正确方法
- angular - ngform 复选框选择数组提交
- java - 基于唯一集在Java中基于List Integer元素创建“序数”集群
- swift - 在 Swift 中将 RGB 转换为十六进制
- mysql - 无服务器在本地工作,但在部署时不工作