As the question says, why is toList (1, 2) == [2]
?
I remember something similar happening when fmapping on tuples, but I do not remember why or if it is related.
(1,2)
does not correspend to the list [1,2]
. That wouldn't make sense: what would then (True, 3.14)
correspend to? You can't have the list [True, 3.14]
, because a list can only contain elements of a single type. (Haskell is different from e.g. Python here.)
The only way to pick elements of guaranteed a single type from any tuple is, well, to take only a single element. Hence toList
, as generated from the Foldable (a,)
instance, takes tuples (a,b)
and yields lists [b]
. Obviously there's always exactly one b
element in such a tuple†.
You could in principle consider (Int, Int)
as a special case where the elements have the same type and hence you can pick two instead of one, but such a special handling would require some highly awkward type-equality checking. And generally, special-case handling is not a good idea.
Arguably, it would have been better not to define the Foldable (a,)
instance at all, to avoid this confusing behaviour. Then again, sometimes it's handy to use fold
to just get rid of the first tuple element (e.g. some index).
b
and not a
? Kind of arbitrary? Well, not completely. (a,b)
is actually syntactic sugar for (,) a b
, hence you can consider (,) a
as a functor (whose elements have type b
), but you can't have a functor (`(,)`b)
whose elements would have type a
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With