Question

I have started learning Haskell a few months ago. Also know programming in another functional language Scheme which uses heterogeneous lists. I would like to know the advantages and disadvantages of both type of lists so that can compare both designs.

Was it helpful?

Solution

Advantages of Homogeneous lists

It all has to do with the types my friend. Like take as an example, type signatures:

concat :: [ByteString] -> ByteString

It is clear from this type signature that it takes a list of strings, and put them together. This wouldn't be possible with heterogeneous lists, because it wouldn't be easy to express a lists type. Another thing to consider is that your functions that have to worry about different types of objects. Another thing to consider is a compromise between heterogeneous and homogeneous lists: existential types.

{-# LANGUAGE ExistentialQuantification #-}

data Showable = forall a. Show a => Pack a
instance Show Showable where
    show (Pack a)=show a

showableList :: [Showable]
showableList = [Pack 1, Pack "Yolo", Pack 5.2, Pack (3, 4), Pack ["A", "B", "C"], Pack 'c']

main=print showableList

This allows the parts of the list to be different types, but they can only be used in the same way. This could work with, say, shapes. If they where all part of a shapes class, you could do thigs like get their area and such, but no their radius.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top