0

Im having trouble inferring the type of this function:

(foldr (.))

I know the types of:

(.) :: (b -> c) -> (a -> b) -> a -> c

foldr :: (a -> b -> b) -> b -> [a] -> b

But now i have no idea what to do.. Is there a method to always be able to infer the type in a systematic way? How would it apply to this case?

Shaeldon
  • 873
  • 4
  • 18
  • 28
Gonzalo_Arcos
  • 150
  • 4
  • 14

1 Answers1

4

I usually follow these steps:

Write their types:

(.) :: (b -> c) -> (a -> b) -> a -> c
foldr :: (a -> b -> b) -> b -> [a] -> b

Make all the type variable name distinct:

(.) :: (b -> c) -> (a -> b) -> a -> c
foldr :: (x -> y -> y) -> y -> [x] -> y

Now since you are applying (.) to the first argument of foldr, you can infer the following relation between the types:

foldr :: (   x ->       y ->         y  ) -> y -> [x] -> y
(.) ::   (b -> c) -> (a -> b) -> (a -> c)

From the above you can infer the following relationship:

x ~ (b -> c)
y ~ (a -> b)
y ~ (a -> c)

From the above y, you can infer that both b and c should be same.

The type of foldr (.) should be:

foldr (.) :: y -> [x] -> y

Now replace y and x with the new derived ones, you will get the required type:

foldr (.) :: (a -> b) -> [b -> b] -> a -> b
Sibi
  • 47,472
  • 16
  • 95
  • 163
  • thanks a lot for your explanation. My only question is, how did you know where to put the parenthesis? By this i mean, couldnt you parenthesized the expression so that x ~ b, y ~ c->a->b, y~ a->c . in this case the type inference is completely different. – Gonzalo_Arcos May 04 '14 at 18:45
  • @user3558296 That's because the type of `(.)` is `(b -> c) -> (a -> b) -> a -> c`. The parenthesis part is already fixed for `(.)`. – Sibi May 04 '14 at 18:48
  • thanks a lot i get it now.. Now i was trying to infer the type of (. flip) using the method you explain and i got : [code] (b -> a -> c1 -> c) -> a -> b -> c1 -> c[/code] however ghci says the type is [code] ((b -> a -> c1) -> c) -> (a -> b -> c1) -> c[/code] why does ghci parenthesize the b->a->c1 expression? – Gonzalo_Arcos May 04 '14 at 19:05