Haskell 中 Pointfree 风格的元素数量
我想定义一个函数来计算列表中满足给定谓词的元素数量:
number_of_elements :: (a -> Bool) -> [a] -> Int
number_of_elements f xs = length (filter f xs)
例如:
number_of_elements (==2) [2,1,54,1,2]
应该返回2。
我们可以写得更短:
number_of_elements f = length . filter f
是否可以不带 f 参数来写?
I want to define a function that computes the number of elements in a list that satisfy a given predicate:
number_of_elements :: (a -> Bool) -> [a] -> Int
number_of_elements f xs = length (filter f xs)
For example:
number_of_elements (==2) [2,1,54,1,2]
should return 2.
We can write it shorter:
number_of_elements f = length . filter f
Is it possible to write it without f parameter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然是:
Sure it is:
我认为您的建议不会比您的建议更具可读性。然而,只是为了好玩,你可以这样做:
或者
I don't think you can get more readable than the what you suggested. However, just for the fun of it you can do this:
or
您可能想了解语义编辑器组合器。从那里获取
result
组合器:result
组合器获取一个函数并将其应用于另一个函数的结果。现在,看看我们拥有的函数:现在,
length
适用于[a]
的;它恰好是foo :: [a] ->; 形式的函数的结果类型。 [a]
。所以,但是
filter
的结果正是一个[a] -> [a]
函数,因此我们要将结果长度
应用于filter
的结果:You might like to read about Semantic Editor Combinators. Take the
result
combinator from there:The
result
combinator takes a function and applies it to the result of another function. Now, looking at the functions we have:Now,
length
applies to[a]
's; which, it happens, is the result type of functions of the formfoo :: [a] -> [a]
. So,But the result of
filter
is exactly an[a] -> [a]
function, so we want to applyresult length
to the result offilter
: