简体   繁体   English

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

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

I designing a function 'total' total:: (Integer -> Integer) -> (Integer -> Integer) such that total f is the function which at value n gives the total f 0 + f 1 + … + fn that uses built in Haskell functions rather than 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: 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]
  |                 ^^^

This is the code that I have written:这是我写的代码:

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

Now I understand what the error is saying (that I need to follow the function declaration), but I am confused as to why Haskell doesn't interpret parenthesis around the second part, and how I am supposed to solve this problem without a list and the mapping function.现在我明白错误在说什么(我需要遵循 function 声明),但我很困惑为什么 Haskell 不解释第二部分周围的括号,以及我应该如何在没有列表和映射 function。 Maybe use Lambda Abstraction?也许使用 Lambda 抽象? I am not sure.我不知道。 How should I approach solving this problem?我应该如何解决这个问题?

You are passing map as an argument to sum , rather than the result of calling map .您将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