something
something

Reputation: 107

Haskell why is [fst,snd] :: [(a,a) -> a]

I am learning Haskell and am wondering why

[fst,snd] :: [(a,a) -> a]

I originally wrote

[fst,snd] :: [(a,b) -> a, (c, d) -> d]

I cannot understand why it is the way it is; could someone please explain?

Thanks

Upvotes: 10

Views: 1613

Answers (1)

Rodrigo Ribeiro
Rodrigo Ribeiro

Reputation: 3218

The point is that lists, in Haskell, are a homogeneous data structure (of course, you can have heterogeneous lists, but it is another story). So, when you use polymorphic functions as lists elements they should have the same type.

In your case you are using fst :: (a , b) -> a and snd :: (a, b) -> b as list elements so, they must have the same type. To ensure the sameness of these types, type inference resort to first-order unification. Unifying

 (a , b) -> a

and

 (a , b) -> b

we notice that the following substitution make these types equal is

 [b +-> a] -- means substitute occurrences of b for a

Applying it to both types, we get

 (a,a) -> a

as Haskell is telling you.

Upvotes: 13

Related Questions