Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why doesn't haskell have heterogeneous lists

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?

like image 857
David K. Avatar asked Nov 28 '22 15:11

David K.


1 Answers

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.

like image 98
ScottWest Avatar answered Jan 17 '23 17:01

ScottWest