Home > Back-end >  Can someone give me an example of a Haskell function of the type (Int->Int)->Int
Can someone give me an example of a Haskell function of the type (Int->Int)->Int

Time:09-10

I have been asked to give an example of a function defined as (Int->Int)->Int in Haskell. No matter how simple.

CodePudding user response:

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:

  • you want to generate an Int
  • but the only argument you can use to do so is a function Int -> Int, for which you are not given an input!
  • So you either
    1. 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
      
    2. or choose a fixed argument for it (as suggested in the other answer), e.g. 6
      f :: (Int -> Int) -> Int
      f g = g 6
      

In the first solution, 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.

In the second solution, f takes g and applies it to 6, no matter what. A better name for this f function would be maybe applyTo6.

CodePudding user response:

(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
  • Related