列表中的 Prolog 元素替换
您好,我想知道您是否可以帮我解决这个问题
:从 Prolog 中编程:编写 Prolog 脚本,用另一个给定元素替换列表中的任何给定元素。例如:
replace( 3, a,[1,2,3,4,3,5], [1,2,a,4,a,5])=true
提前非常感谢
Hi i was wondering if you could help me out with this
From programming in Prolog: write Prolog script for replacement any given element in lists by an another given element. For example:
replace( 3, a,[1,2,3,4,3,5], [1,2,a,4,a,5])=true
Many Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在Prolog中,大多数列表处理是通过处理头部然后递归处理列表的其余部分来完成的。当然,您不能忘记基本情况,它是一个空列表。
用空列表中的任何内容替换任何内容会再次产生空列表。如果列表头与要替换的元素相同,则替换它,否则,保持原样。在这两种情况下,都会递归处理列表的其余部分。从英文翻译成 Prolog:
In Prolog, most list processing is done by processing the head and then recursively processing the rest of the list. Of course, you can't forget about the base case, which is an empty list.
Replacing anything with anything in an empty list results again in an empty list. If the head of the list is the same as the element to replace, replace it, otherwise, keep it as it is. In both cases, process recursively the rest of the list. Translated from English into Prolog:
到目前为止,其他答案中提出的所有实现在与非基础术语一起使用时在逻辑上都是不合理的。考虑原始查询和一个轻微的变体:
它有效!让我们问一些非常相似的问题:
发生了什么?将归咎于元逻辑内置函数
(!)/0 和
(\=)/2
,它们很难正确使用,并且常常使代码变得脆弱、不纯粹且逻辑上不健全。为了保持逻辑的健全性,坚持逻辑的纯粹性并尽可能避免使用元逻辑“特征”!幸运的是,大多数 Prolog 实现都支持
dif/2
作为(\=)/2
的逻辑替代。让我们使用它:让我们再次运行上面的查询,这次使用改进的
replaceP/4
:All implementations presented so far in other answers are logically unsound when being used with non-ground terms. Consider the original query and a slight variant:
It works! Let's ask some very similar queries:
What's going on? Put the blame on meta-logical builtins
(!)/0
and(\=)/2
, which are very hard to use right and often make code brittle, impure, and logically unsound.To preserve logical soundness, stick to logical purity and abstain from meta-logical "features" whenever possible! Luckily, most Prolog implementations support
dif/2
as a logical alternative to(\=)/2
. Let's use it:Let's run above queries again, this time with the improved
replaceP/4
:不过,人们通常会将 3.arg 安排为第一个。严格来说,上面并没有替换列表中的任何内容,它只是回答第四个参数是否与第三个参数类似,但用 Y' 而不是 X'。
Though, one would usually arrange the 3. arg to be the first one. And strictly speaking above does not replace anything in the list, it just anwsers if 4th arg is like the one in the 3rd but with Y' instead of X'.
想法很简单,如果元素匹配,则更改它,如果不匹配,则继续,直到为空。
the idea is simple, if the elements match, change it, if not, go forward until empty.