首页 > 解决方案 > 如何在 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

标签: listsearchprologpredicate

解决方案


你可以用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.

推荐阅读