What is the problem with this code?
addNum :: Int->Int-> Int
addNum a b = a+b
divideby :: ( Int->Int -> Int ) -> Int ->float
divideby f z = f /z
I want to take the addNum function as an input to divideby with a divisor and then output the answer. So the divideby function should act as a higher order function.
What is the problem with this code? It gives following error:
*** Expression : f / z
*** Term : f
*** Type : Int -> Int -> Int
*** Does not match : Int
It means exactly what the error says. You have specified that the type of your function is
That means, the first argument must be a function, with the type
Int->Int -> Int, and the second input must be anInt, and then it will produce afloat. Naturally, Haskell does not know how to divide a function by an Int, which is what you are telling it to do with the expressionf / z.In response to the comment: no. That is not a higher-order function, but it is close. Take a look:
divideByis a function that takes 3Ints as input, and produces anInt. Since its inputs are merelyInt, it is not a higher-order function. However, you could abstract the use ofaddNuminto an input, thus making it a higher-order function.addNumhas type(Int -> Int -> Int), so, in addition to the inputs we have already, we will make that the type of our first inputThis is a higher-order function, that also compiles correctly and has meaning. 🙂 You can pass
addNumas an input to this function.