问题描述
我需要开发自己的过滤器功能,类似于filter
在Haskell中的工作方式,但是要使用列表理解和谓词.因此,我将lcFilter (>3) [1,2,3,4,5,6,10,444,3]
放入ghci,它将打印所有大于3的数字.
I need to develop my own filter function similar to how filter
works in Haskell but by using list comprehension and a predicate. So I would put lcFilter (>3) [1,2,3,4,5,6,10,444,3]
in ghci and it would print all numbers greater than 3.
我的代码基于我擅长的递归示例,但似乎无法转换为列表理解.无论我在[x | x<-xs, p]
中输入什么内容,它都会缝在一起,它总是会引发编译器错误.我知道p
部分是错误的.我已经尝试过==p
,xs==p
以及几乎所有我能想到的东西.这使我认为其他部分可能是错误的,但我真的不确定.
My code is based on a recursion example which I'm good at but I can't seem to convert to list comprehension. It seams no matter what I put in [x | x<-xs, p]
it always throws a compiler error. I know the p
part is wrong. I've tried ==p
, xs==p
and just about everything else I could think of. This makes me think some other part might be wrong but I'm really not sure.
这是我的函数lcFilter
的代码.我不确定是部分还是全部错误,所以我要发布整个内容.
Here is the code for my function lcFilter
. I'm not sure if some or all of it is wrong so I'm posting the whole thing.
lcFilter :: (a -> Bool) -> [a] -> [a]
lcFilter _ [] = []
lcFilter p (x:xs) = [x | x<-xs, p]
如果我键入lcFilter (>3) [1,2,3,4,5]
,它应该像标准的Haskell filter
函数一样打印[4,5]
.
If I type lcFilter (>3) [1,2,3,4,5]
it should print [4,5]
just like the standard Haskell filter
function.
推荐答案
就像
[x | x <- xs, p x]
由于p :: a -> Bool
和xs :: [a]
,要获取布尔值,我们需要将该函数 apply 应用于自变量;通过列表理解语义,我们可以得到x :: a
.
Since p :: a -> Bool
, and xs :: [a]
, to get a Boolean we need to apply the function to an argument; and by the list comprehension semantics we have x :: a
.
类型推断的应用规则为
x :: a
p :: a -> b
---------------
p x :: b
并且您不需要模式匹配,列表理解将解决这个问题.
And you don't need the pattern matching, list comprehension will take care of that.
总的来说,是
lcFilter :: (a -> Bool) -> [a] -> [a]
lcFilter p xs = [x | x <- xs, p]
列表理解很有趣.他们遵循的一条规则是
List comprehensions are fun. One rule they follow is
[ ... | x <- (xs ++ ys), .... ] ===
[ ... | x <- xs, .... ] ++ [ ... | x <- ys , .... ]
因此,我们也有
[ ... | x <- ([y] ++ ys), .... ] ===
[ ... | x <- [y], .... ] ++ [ ... | x <- ys , .... ] ===
[ ...{x/y} | ....{x/y} ] ++ [ ... | x <- ys , .... ]
其中{x/y}
表示将x
替换为y
" .因此,列表[a,b,...,n]
根据您的定义转换为
where {x/y}
means "replace x
by y
throughout". Thus, a list [a,b,...,n]
is transformed by your definition into
[ a, b, ..., n ] ===>
[ a | p a] ++ [b | p b] ++ ... ++ [n | p n ]
这可以通过/作为 monads 或 monoids 的概念的一个很好的例证来进一步理解,但是我们将其留给其他人天. :)
This can be further understood in terms of / serve as a nice illustration to / the concepts of monads, or of monoids, but we'll leave that for another day. :)
这篇关于使用列表理解的谓词自定义过滤器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!