繁体   English   中英

Haskell function 计算 f 0 + f 1 + ... + fn 而没有显式递归

[英]Haskell function that evaluates f 0 + f 1 + … + f n without explicit recursion

我设计了一个 function 'total' total:: (Integer -> Integer) -> (Integer -> Integer)这样总 f 就是 function ,它的值 n 给出了总 f 0 + f 1 + … + fn 使用在 Haskell 函数中,而不是显式递归。

Now, my first instinct was to use the map function to apply said function to a list of Integers [1..n], then use the sum function in order to calculate this, but it is erroring out on me and giving this message:

code.hs:8:17: error:
    • Couldn't match type ‘[b0]’ with ‘[Integer] -> Integer’
      Expected type: (a0 -> b0)
                     -> (Integer -> Integer) -> [Integer] -> Integer
        Actual type: (a0 -> b0) -> [a0] -> [b0]
    • In the first argument of ‘sum’, namely ‘map’
      In the expression: sum map (f) [1 .. n]
      In an equation for ‘total’: total f n = sum map (f) [1 .. n]
  |
8 | total f n = sum map (f) [1..n]
  |                 ^^^

这是我写的代码:

total :: (Integer -> Integer) -> (Integer -> Integer)
total f n = sum map (f) [1..n]

现在我明白错误在说什么(我需要遵循 function 声明),但我很困惑为什么 Haskell 不解释第二部分周围的括号,以及我应该如何在没有列表和映射 function。 也许使用 Lambda 抽象? 我不知道。 我应该如何解决这个问题?

您将map作为参数传递给sum ,而不是调用map结果

total f n = sum (map f [1..n])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM