I don't understand why I can't construct a list that looks like [1,"1",1.1]
in haskell. I don't think it's static typing that gets in the way because I thought that head
would now have an ill defined type but then I thought about it and there is no reason the run-time system doesn't instantiate a different version of head
whenever a list is fed into it so head [1,"1",1.1]
would be typed as List->Int
and head (tail [1,"1",1.1])
would be typed as List->String
. Since the run-time already does a lot of bookkeeping why doesn't it provide fancier polymorphic (or is it generic) versions of the various prelude functions? What am I missing here?
It is indeed the typing that prevents this. Consider the definition of a list (notice the type parameter a
, which is missing from your types):
data List a = Nil | Cons a (List a)
In the Cons a (List a)
you can see that the type of thing at the head of the list must be the same type as the elements that follow it. To answer your question, you're not missing a lot: as you say the runtime could do it, but in Haskell you want to make these typing decisions at compile-time, not runtime.
If you want heterogeneous lists, you can see some wizardry by Oleg Kiselyov in his work on HList (= Heterogeneous List). It may not be exactly what you want, but it's in the same rough direction.
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