I have been asked to give an example of a function defined as (Int->Int)->Int in Haskell. No matter how simple.
I have been asked to give an example of a function defined as (Int->Int)->Int in Haskell. No matter how simple.
(Int -> Int) -> Int is a function of one argument. The type of the argument is Int -> Int, and the return type is Int
The argument has type Int -> Int, which means that it's also a function of one argument. This function's argument is of type Int and its return type is Int
The simplest example would be probably this:
f :: (Int -> Int) -> Int
f g = g 42
As explained, (Int -> Int) -> Int is the type of a function producing an Int from another function, which in turns produces an Int from an Int.
How simple can such a function be?
Think about it:
IntInt -> Int, for which you are not given an input!ignore that input function entirely and choose a result for your function, e.g. 6
f :: (Int -> Int) -> Int
f _ = 6 -- _ means that I don't even bother
-- giving a name to the argument,
-- as I don't use it
So f simply ignores its only argument and always gives you back 6. Now look at const's description and examples. Oh, but that gives us a way to implement f,
f :: (Int -> Int) -> Int
f = const 6
which also gives us the chance to choose a more appropriate name for f: always6.
or choose a fixed argument for it (as suggested in the other answer), e.g. 6
f :: (Int -> Int) -> Int
f g = g 6
Here f takes g and applies it to 6, no matter what. A better name for this f function would be maybe applyTo6.