Prolog:过滤列表? [英] Prolog: Filtering a list?
问题描述
我目前正在 Prolog 上进行一个非常短的项目,但在尝试将我创建的过滤器"应用到列表时遇到了困难.我准备好了你可以称之为过滤器的东西,但我不能应用它.最好能说明一下:
I'm currently working on a very short project on Prolog, and just got stuck trying to apply a "filter" I have created to a list. I have what you could call the filter ready, but I can't apply it. It'd be better if I illustrate:
filter(A, B)
...如果满足某些条件,则输出真".
...outputs 'true' if certain conditions are met.
filterList(A, [X, Y, Z])
...输出一个列表,其中包含来自第二个参数的所有元素,这些元素使过滤器输出 false.(因此,如果 filter(A, X) 为真,则输出为 [Y, Z] ).
...outputs a list which includes all elements from the second argument that make the filter output false. (So if filter(A, X) is true, the output is [Y, Z] ).
我已经准备好了过滤器"函数,但现在我需要将它应用到一个列表中,如第二个示例所示,排除在应用第一个参数时过滤器返回 true 的所有元素.
I have the "filter" function ready, but now I need to apply it to a list as shown on the second example, excluding all elements for which the filter returns true when applied with the first argument.
因此,如果过滤器是一个简单的 A == B,则该函数应该接收 A [A,B,A,C,D,A] 并输出 [B,C,D],已删除所有显然,过滤器适用的元素.
So, if the filter is a simple A == B, the function is supposed to receive A [A,B,A,C,D,A] and output [B,C,D], having removed all the elements for which the filter applies, obviously.
我在函数的基本结构方面遇到了问题,所以如果有人可以为这样的函数提供一个基本的大纲,那将会有很大的帮助.我已经尽可能地简化了我的情况,所以我可以接受你能提供的任何东西,并根据我的需要进行修改.
I'm having trouble with the basic structure of the function, so if anyone could supply a basic outline for a function such as this it would be of great help. I've simplified my situation as much as possible so I can take whatever you may be able to provide and modify it for my needs.
提前致谢!
推荐答案
如果你在 Prolog 中搜索高阶函数,你应该明确地咨询 Naish (1995),这是一个非常好的资源.
If you are searching for higher-order functions in Prolog, you should definetly consult Naish (1995), a very good resource on this.
他对filter/3
的定义如下(他使用差异列表表示法,因此不必定义filter/4
):
His definition of filter/3
is the following (he uses difference-list notation, therefore escapes having to define filter/4
):
filter(_,[],[]).
filter(P, A0-As0, As) :-
(
call(P, A0) -> As = A0-As1
;
As = As1
)
, filter(P, As0, As1).
我对这个谓词有疑问,请在评论中问我.也强烈推荐阅读论文,它还定义了map
、foldr
和compose
!请注意,他提到的许多限制(例如,缺少 call/3
或更高阶的 apply
不再适用.SWI-Prolog 具有 =..
运算符,它解决了他的所有问题并使任意 n 阶逻辑成为可能.
I you have questions about this predicate, please ask me in the comment. Reading the paper is also highly recommended, it also definess map
, foldr
and compose
! Note that many of the limitations he mentions (like, for example a missing call/3
or a higher-order apply
do not apply anymore. SWI-Prolog has the =..
operator, which addresses all of his concerns and makes arbitrary n-order logic possible.
这篇关于Prolog:过滤列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!