Haskell 中 Pointfree 风格的元素数量

发布于 2024-12-22 17:11:25 字数 388 浏览 0 评论 0原文

我想定义一个函数来计算列表中满足给定谓词的元素数量:

  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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

長街聽風 2024-12-29 17:11:25

当然是:

number_of_elements = (length .) . filter

Sure it is:

number_of_elements = (length .) . filter
俏︾媚 2024-12-29 17:11:25

我认为您的建议不会比您的建议更具可读性。然而,只是为了好玩,你可以这样做:

numberOfElements = (.) (.) (.) length filter

或者

(.:) = (.) . (.)
numberOfElements = length .: filter

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:

numberOfElements = (.) (.) (.) length filter

or

(.:) = (.) . (.)
numberOfElements = length .: filter
水水月牙 2024-12-29 17:11:25

您可能想了解语义编辑器组合器。从那里获取 result 组合器:

result :: (output -> output') -> (input -> output) -> (input -> output')
result = (.)

result 组合器获取一个函数并将其应用于另一个函数的结果。现在,看看我们拥有的函数:

filter :: (a -> Bool) -> [a] -> [a]
length :: [a] -> Int

现在,length 适用于 [a] 的;它恰好是 foo :: [a] ->; 形式的函数的结果类型。 [a]。所以,

result length :: ([a] -> [a]) -> ([a] -> Int)

但是 filter 的结果正是一个 [a] -> [a] 函数,因此我们要将 结果长度 应用于 filter 的结果:

number_of_elements = result (result length) filter

You might like to read about Semantic Editor Combinators. Take the result combinator from there:

result :: (output -> output') -> (input -> output) -> (input -> output')
result = (.)

The result combinator takes a function and applies it to the result of another function. Now, looking at the functions we have:

filter :: (a -> Bool) -> [a] -> [a]
length :: [a] -> Int

Now, length applies to [a]'s; which, it happens, is the result type of functions of the form foo :: [a] -> [a]. So,

result length :: ([a] -> [a]) -> ([a] -> Int)

But the result of filter is exactly an [a] -> [a] function, so we want to apply result length to the result of filter:

number_of_elements = result (result length) filter
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文