Why do we use tuples, if we can use a two dimensional list?
Because lists and tuples are conceptually different things, and the type system gives us an useful way to state and recognise the difference in code. For one of many possible examples, one might define...
type ListyPair a = [a]
... and then...
listyFst :: ListyPair a -> a
listyFst [x, _] = x
listySnd :: ListyPair a -> a
listySnd [_, y] = y
... so that:
GHCi> listyFst [3,4]
3
GHCi> listySnd [3,4]
4
But what happens if the listy "pair" has just one element, or none? We would have to throw a runtime error (yuck), or make listyFst
and listySnd
result in a Maybe a
so that we can handle failure cleanly. What if the "pair" has more than two elements? Should we just discard them silently, or would it be better to make the functions fail in this case as well?
From the perspective of a strong type system user, when we replace an actual pair with ListyPair
we are throwing away useful information. Knowing that there are really just two elements allows us to avoid all of the complications above.
realFst :: (a, b) -> a
realFst (x, _) = x
realSnd :: (a, b) -> b
realSnd (_, y) = y
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…