如何在PROLOG中查找一个列表中的值?

问题描述 投票:1回答:1

到目前为止,我已经做了相当多的研究,我已经尝试了不同的方法,然而即使阅读了多个堆栈溢出的答案,甚至阅读了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

list search prolog predicate
1个回答
3
投票

你可以用 member/2 [swi-doc]. 这可以用来搜索,与成员统一,或生成一个列表。

所以你可以用:

search(Note, Scale, Item) :-
    scale(Note, Scale, Items),
    member(Item, Items).

重要的是 Note, Scale, ItemItems 开头 Uppercase,因为小写的标识符是常量或漏斗。大写的标识符为 变量.

因此,这将统一 Item 与列表中的项目,对于给定的样本数据,例如我们得到。

?- search(c, minor, Item).
Item = c ;
Item = d ;
Item = e_b ;
Item = f ;
Item = g ;
Item = a_b ;
Item = b_b.
© www.soinside.com 2019 - 2024. All rights reserved.