[Haskell-cafe] Re: Non Empty List?
rendel at cs.au.dk
Fri Jun 5 16:01:04 EDT 2009
please write to the whole list, not just me. There are a lot of people
around who can help you.
> Rendel do you mind to explain to me how Container a = Many a
> (Container [a]) prevents user from creating an empty list?
> I did try the following:
> let a = Many "string"
> a :: Container [Char] -> Container [Char]
> let b = Many 
> b :: forall a. Container [a] -> Container [a]
> but I can not understand what is the difference.
You cannot prevent users from creating an empty list, because lists are
already defined in the Haskell prelude, and you cannot change that
definition. But you can define your own datatype Container which
prevents users from creating empty containers.
data Container a = Many a (Container [a])
is quite complicated, because you have (Container a) on the left hand
side of the equation, but (Container [a]) on the right hand side. Is
that on purpose?
Anyway, your Container has the property that a (Container a) is never
empty, because it always contains at least one value of type a, namely
the first parameter of Many. To see that, we can write a function which
extracts that element:
getContainerElement :: Container a -> a
getContainerElement (Many element something) = element
It is not possible to write such a function for ordinary lists without
calling error or entering a nonterminating loop:
getListElement :: [a] -> a
getListElement (element : something) = element
getListElement  = error "no element around :("
So ordinary lists can be empty, but your Containers can't.
More information about the Haskell-Cafe