从列表中删除简单的 Prolog [英] Simple Prolog delete from list

查看:81
本文介绍了从列表中删除简单的 Prolog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(这不是一个课程作业问题.只是我个人的学习.)

我正在尝试在 Prolog 中进行练习以从列表中删除元素.这是我的代码:

deleteall([],X,[]).deleteall([H|T],X,Result) :-H==X,删除所有(T,X,结果).deleteall([H|T],X,[H|Result]) :- deleteall(T,X,Result).

当我测试它时,我首先得到了一个很好的答案(即删除了所有的 X.)但随后回溯为我提供了列表的所有其他变体,其中一些 X 的实例被删除,或者没有.

为什么会这样?为什么 H==X 会落到最后一个子句?

解决方案

最后一个子句说当从列表中删除 X 时,头元素可能会保留(独立于它的值).Prolog 可以在它认为合适的任何时候使用这个子句,而不管前面子句中的条件是否为真如果另一个子句失败,或者如果你指示它这样做(例如,通过在顶层发出 ; 以获得下一个解决方案).如果你添加一个条件,head 元素可能不等于 X,它应该可以工作.

删除了我最初打开的错误断言.

(This is NOT a coursework question. Just my own personal learning.)

I'm trying to do an exercise in Prolog to delete elements from a list. Here's my code :

deleteall([],X,[]).
deleteall([H|T],X,Result) :- 
    H==X,
    deleteall(T,X,Result).
deleteall([H|T],X,[H|Result]) :- deleteall(T,X,Result).

When I test it, I first get a good answer (ie. with all the Xs removed.) But then the backtracking offers me all the other variants of the list with some or none of the instances of X removed.

Why should this be? Why do cases where H==X ever fall through to the last clause?

解决方案

The last clause says that when removing X from a list, the head element may stay (independently of its value). Prolog may use this clause at any time it sees fit, independently of whether the condition in the preceding clause is true or not backtrack into this clause if another clause fails, or if you direct it to do so (e.g. by issuing ; in the top-level to get the next solution). If you add a condition that the head element may not equal X, it should work.

Edit: Removed the incorrect assertion I originally opened with.

这篇关于从列表中删除简单的 Prolog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆