This question is focused specifically on list of tuples.
I was using sort
to sort a list of tuples; at first I thought ghci would raise an error or something, but instead I received a sorted list based on the first element of my tuple!
Prelude Data.List> :t sort
sort :: Ord a => [a] -> [a]
Prelude Data.List> sort [3,1,2]
[1,2,3]
Prelude Data.List> sort [(3,'c'), (1,'a'),(2,'b')]
[(1,'a'),(2,'b'),(3,'c')]
Prelude Data.List> sort [(3,'c',1), (1,'a',2),(2,'b',3)]
[(1,'a',2),(2,'b',3),(3,'c',1)]
The same happens to functions with similar behaviors like minimum
but not to those like any
. So I guess this is a syntax sugar (Haskell always has some syntaxes that I have no idea about), but I'm not sure if this applies to other (Foldable t, Ord a) => t a
types, nor if this is a more generic feature.
How does Haskell treat a tuple of type (a,b)
so that f :: ([a] -> [c])
can be apply to l :: [(a, b)]
? And does this way apply to other data structures or this is more like list-only?
Ord
ered: the first components is compared first. On a tie, the second components are compared, And so on. So a list of tuples is a list of ordered elements, and can be sorted. – chisort :: forall a. Ord a => [a] -> [a]
choosesa
to be(Int, Char)
, then provides evidence that(Int, Char)
is an instance ofOrd
. Type variables can be instantiated to be any (monomorphic) type, includingInt
and tuples and lists and trees andBool
s and whatever floats your boat. – Daniel Wagner