prolog - 如果 # 是 List 的第一个元素,则 Prolog 谓词返回 true
问题描述
我想编写一个接收列表的谓词,如果列表的第一个元素是“#”,则该谓词为真,但我不希望它统一,以防万一。
例如
? - List=[#, _ , _ ,_]
? - mypredicate(List)
true.
? - List=[_,#, _ , _ , _]
? - mypredicate(List)
False.
我写的是:
mypredicate([L]) :-
nth0(0, L, #).
问题是,如果第一个元素不是“#”,那么它会通过将 # 统一到第一个元素来更改列表 L。我不希望它统一,我只是希望它检查它的真假。
我还需要一个不同的谓词来验证“#”是否是列表的最后一个元素,我写道:
mypredicate2(L) :-
last(L, #).
两个谓词的问题是相同的,如果它还不是#,它将原始列表的元素更改为#。我不希望它统一。
解决方案
You can make use of ==/2
[swi-doc] to check if:
True
ifTerm1
is equivalent toTerm2
. 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.
推荐阅读
- android - 在更新到目标 sdk 29 之前,Javascript 无法在 Android WebView 上运行
- javascript - 从 useReducer Hook 返回的状态是“深拷贝”还是 reducers 输出的引用?
- css - 背景图像不透明度会影响其顶部的图标
- python-3.x - 访问已删除然后重新创建的全局变量
- python - sklearn /scikit 使用 fit 方法学习
- node.js - 从多表单数据中删除换行符。节点
- html - 如何在 div 中为 CSS 选择多个元素
- python - 如何使用正则表达式将字符串元素转换为列表?
- python - 无法使用 Python 从 html 文件中提取查找/提取所有标签
- node.js - 节点将数据从一个视图解析到另一个视图