简体   繁体   中英

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.

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. Maybe use Lambda Abstraction? 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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