List types

Koen Claessen koen@cs.chalmers.se
Sun, 3 Dec 2000 14:36:00 +0100 (MET)


Eric Allen Wohlstadter asked:

 | Is there a way to make a list that contains multiple
 | types? If not, why, and isn't this a serious
 | restriction? I would like to be able to say:
 :  
 | 	map show ['a',5]

Fergus Henderson replied:

 | You can't do it in standard Haskell, but with ghc
 | extensions you can achieve the same effect.
 :
 | 	data Showable = forall a . Show a => Showable a
 | 	instance Show Showable where
 | 		show (Showable x) = show x
 | 	
 | 	example = map show [Showable 'a', Showable 5]

You can also do this in Hugs. But you do not need GHC's or
Hugs' extensions to achieve Fergus' effect:

  data Showable = Showable String

  instance Show Showable where
    show (Showable s) = s

  showable :: Show a => a -> Showable
  showable x = Showable (show x)

  example = map show [showable 'a', showable 5]

(This kind of trick can often be applied in the case of
using existential types.)

But this is not a solution to Eric's problem! Eric would
have been better off by just saying:

  map id [show 'a', show 5]

or of course even:

  [show 'a', show 5]

Which is simpler, easier to understand and cheaper. This is
not a solution to his original problem, but merely a
workaround.

The idea is to not wait until you are taking the elements
out of the list before showing them, but do it already when
you put them into the list. In a lazy functional language,
they will only be evaluated anyway when you actually use the
showed elements.

/Koen.

--
Obprogram:
cool=putStr.concatMap(("\27];"++).(++"\7").take 80).iterate tail.cycle