dasogom
dasogom

Reputation: 55

Haskell Higher order function Type

I am studying haskell now. But I am struggling with 'Type'.

  1. For example, type of f function is

f g (x,y)= g x y

(a -> b -> c) -> (a, b) -> c

  1. type of the following Haskell function h

h f g x y = f (g x y) x

(a -> b -> c) -> (b -> d -> a) -> b -> d -> c

How can I understand how to guess type of function?

Upvotes: 1

Views: 160

Answers (1)

Robin Zigmond
Robin Zigmond

Reputation: 18249

I'll walk you through the first one: hopefully this gives you enough of an idea that you can figure out the second one by yourself.

So the function definition is:

f g (x,y)= g x y

f is the function we're interested in, and we can see from the above - just from the left hand side in fact - that it takes 2 arguments: g and the tuple (x,y). So let's use some type variables:

  • we'll use a for the type of g
  • b for the type of x
  • c for the type of y
  • and d for the type that f outputs when given the two arguments.

This gives us

f :: a -> (b, c) -> d

and further that is all the information that we can get from the left of the =. We can learn more by looking at the right hand side - the g x y which must be of type d.

Well the expression g x y itself tells us that g is a function which can take 2 arguments. And further we have already assigned types to those arguments - and to its return value (since this is the same value that f g (x,y) outputs, which we already said has type d).

Writing it all out, we find that the type of g is simply b -> c -> d. Substituting that in the type of f which we wrote down above, we get:

f :: (b -> c -> d) -> (b, c) -> d

If we cared, we could rename the type variables now so that this matches the signature you were given - but hopefully you can see that they're the same without having to do that.

As I said, although slightly more involved, the second exercise can be solved using exactly the same logic.

Upvotes: 4

Related Questions