Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between similarly parenthesized function types

I'm really stuck with functions types in Haskell. There are the types of two functions given and I cannot explain what's the real difference between those.

a :: Int -> (Int -> (Int -> (Int -> Int)))

b :: (((Int -> Int) -> Int) -> Int) -> Int

I still don't get the point. I know what the purpose of currying is -- but I cannot see the concept of currying in this example!

function a: an Int is passed in, and the result is another that takes an Int ... and so on.

function b: How is this different from function A?

like image 247
Toralf Westström Avatar asked Apr 21 '26 01:04

Toralf Westström


2 Answers

Perhaps the best thing to do is to think about two simpler functions:

f :: a -> (b -> c)
g :: (a -> b) -> c

Let's look at these functions in turn.

The first function, f, takes a single parameter of type a, and returns a function of type b -> c. In other words, you could write something like the following, assuming x :: a, y :: b, and z :: c:

f :: a -> (b -> c)
f x = f'
  where f' :: b -> C
        f' y = z

Another way to write the signature of f is as:

f :: a -> b -> c

This works because by default we bind -> to the right. It also gives us another equivalent way of understanding f: it can be thought of a function that takes two parameters, of type a and b, and produces a result of type c.

The second function, g takes one argument, which is a function of type a -> b.

g :: (a -> b) -> c
g h = z
  where h :: a -> b

Thus the two are very different.

Applying this to your functions, the first function takes 4 values of type Int and returns an Int. The second function takes a single function of type ((Int -> Int) -> Int) -> Int, and that's a function that takes a third function of type (Int -> Int) and produces an Int, and so on.

like image 189
Nicolas Wu Avatar answered Apr 22 '26 17:04

Nicolas Wu


Function b takes a function as its argument - it does not produce a function as its result. That is a big difference:

a 42 will produce a function that takes additional arguments. b 42 will produce a type error because 42 is not a function. b myfun where myfun has type ((Int -> Int) -> Int) -> Int) will produce an Int. a myfun will cause a type error because myfun is not an integer.

like image 39
sepp2k Avatar answered Apr 22 '26 18:04

sepp2k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!