Reputation: 69
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.
Upvotes: 2
Views: 251
Reputation: 53911
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.
Upvotes: 4