如何在 PROLOG 中的谓词列表中查找值
How to look up a value inside a list in a predicate, in 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).
我在尝试什么?很简单,可以遍历谓词 scale(c, [c, d, e, f, g, a, b])。但我做不对。
编辑:我有多个谓词,因为其他人建议创建一个谓词来区分一个量表和另一个量表。我以为我可以将它塞进任何算法中,但我想 PROLOG 不是那么宽松 :p
你可以用 member/2
[swi-doc] 做到这一点。这可用于搜索、与成员统一或生成列表。
因此您可以搜索:
search(Note, Scale, Item) :-
scale(Note, Scale, Items),
<b>member(</b>Item, Items<b>)</b>.
Note
、Scale
、Item
和 Items
以 U 大写字母开头很重要,因为标识符小写的是常量或函子。大写的标识符是 variables.
这将因此统一 Item
与列表中的项目,对于给定的样本数据,我们例如获得:
?- search(c, minor, Item).
Item = c ;
Item = d ;
Item = e_b ;
Item = f ;
Item = g ;
Item = a_b ;
Item = b_b.
到目前为止,我已经做了相当多的研究并尝试了不同的方法,但是即使在阅读了多个堆栈溢出答案甚至来自 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).
我在尝试什么?很简单,可以遍历谓词 scale(c, [c, d, e, f, g, a, b])。但我做不对。
编辑:我有多个谓词,因为其他人建议创建一个谓词来区分一个量表和另一个量表。我以为我可以将它塞进任何算法中,但我想 PROLOG 不是那么宽松 :p
你可以用 member/2
[swi-doc] 做到这一点。这可用于搜索、与成员统一或生成列表。
因此您可以搜索:
search(Note, Scale, Item) :-
scale(Note, Scale, Items),
<b>member(</b>Item, Items<b>)</b>.
Note
、Scale
、Item
和 Items
以 U 大写字母开头很重要,因为标识符小写的是常量或函子。大写的标识符是 variables.
这将因此统一 Item
与列表中的项目,对于给定的样本数据,我们例如获得:
?- search(c, minor, Item).
Item = c ;
Item = d ;
Item = e_b ;
Item = f ;
Item = g ;
Item = a_b ;
Item = b_b.