首页 > 解决方案 > 如果 # 是 List 的第一个元素,则 Prolog 谓词返回 true

问题描述

我想编写一个接收列表的谓词,如果列表的第一个元素是“#”,则该谓词为真,但我不希望它统一,以防万一。

例如

? - List=[#, _ , _ ,_]

? - mypredicate(List)
true.

? - List=[_,#, _ , _ , _]

? - mypredicate(List)
False.

我写的是:

mypredicate([L]) :-
    nth0(0, L, #).

问题是,如果第一个元素不是“#”,那么它会通过将 # 统一到第一个元素来更改列表 L。我不希望它统一,我只是希望它检查它的真假。

我还需要一个不同的谓词来验证“#”是否是列表的最后一个元素,我写道:

mypredicate2(L) :-
    last(L, #).

两个谓词的问题是相同的,如果它还不是#,它将原始列表的元素更改为#。我不希望它统一。

标签: prolog

解决方案


You can make use of ==/2 [swi-doc] to check if:

True if Term1 is equivalent to Term2. A variable is only identical to a sharing variable.

So here you can write a predicate that looks like:

mypredicate([X|_]) :-
    X == # .

I leave the predicate that checks if the last item is a # as an exercise.


推荐阅读