Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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

like image 974
something Avatar asked Feb 23 '16 11:02

something


People also ask

What kind of functions are FST and SND?

Functions like fst and snd , which can handle arguments of any type are called (parametric) polymorphic functions.

How do you delete an element from a list in Haskell?

You first compare the head of the list ( y ) to the item you want to remove and correctly return the item or an empty list using areTheySame . Then you want to recursively continue using removeItem on the rest of the list ( ys ).


1 Answers

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.

like image 187
Rodrigo Ribeiro Avatar answered Oct 12 '22 15:10

Rodrigo Ribeiro