[Haskell-cafe] Re: Non Empty List?

Tillmann Rendel rendel at cs.au.dk
Thu Jun 4 19:56:16 EDT 2009


Hi Günther,

GüŸnther Schmidt wrote:
>>> data Container a = Single a | Many a [a]      but the problem above 
> 
> I need a data structure as in my example without the [] being possible 
> to be empty.

So lets write a variant of list which cannot be empty. A usual list is 
empty, or a head and a tail:

   data List a
     = Empty
     | HeadAndTail a (List a)

Now, our kind of list should be just one element, or a head and a tail:

   data NonEmptyList a
     = JustOne a
     | HeadAndNonEmptyTail a (NonEmptyList a)

So we can replace [] by NonEmptyList in your definition to get what you 
want:

   data Container a
     = Single a
     | Many a (NonEmptyList a)

However, since Container and NonEmptyList are isomorphic, we can use one 
instead of the other:

   data Container a
     = Single a
     | Many a (Container a)

Whether this is a good idea depends on the purpose of the types, but I 
guess it is.

   Tillmann


More information about the Haskell-Cafe mailing list