2

I am on a problem that asked to write a function that applies a function to an Integer and calculate the answer. Here is the problem:

Declare the type and define a function that takes a function (say f) and an integer (say n) and returns f 0 + f 1 + f 2 + … + f n. For example, fun sq 5 would returns 55 which is 0+1+4+9+16+25 (“sq” means “square”).

Does anyone know how to do that? I would very much appreciate it.

0

1 Answer 1

4

This is called a higher order function

fun :: (Int -> Int) -> Int -> Int
fun f n = ???

And we just use f like a normal function, writing f 0 or whatever. ??? is the haskell translation of

 f 0 + f 1 + ... + f n

As for how to do this, this looks like homework so I'll just hint you to look at using [0..n] to get a list from 0 to n and

map :: (Int -> Int) -> [Int] -> [Int] -- restricting for clarity

which applies a function to every item in a list (hey it's another higher order function)

sum :: [Int] -> Int

Which adds up all the numbers in a list.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 But can't the type be generalized to Num a => (Int -> a) -> Int -> a ? (Though I agree this homework question is likely expecting your answer)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.