[Haskell-cafe] Re: Non Empty List?

MH mhamro at gmail.com
Fri Jun 5 17:58:45 EDT 2009


I actually meant

data Container a = Many a(Container a)

but here is what I don't understand (fyi, I am a beginner) how can you
construct  this container? I can do

let a = Many "somestring" - and I will get back a function but I can not do
let a = Many 'a' "somestring"  - because the second param is not
(Container a) type.
let a = Many 'a' (Container ['a','a']) - doesn't work either because
Container is a type not a constructor (right or I am missing
something?).

So I have two questions:
1. When I do
let b = Many "somestring" , I get
:t b
b :: Container[Char] -> Container[Char]
what is it and why I am allowed to pass just one parameter to Many
(and how can I use it)?

2. How can you construct that container?
data Container a = Many a(Container a)
let a = ????

On Fri, Jun 5, 2009 at 4:01 PM, Tillmann Rendel<rendel at cs.au.dk> wrote:
> Hi,
>
> please write to the whole list, not just me. There are a lot of people
> around who can help you.
>
> MH wrote:
>>
>> 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.
>
> Your datatype
>
>  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.
>
>  Tillmann
>


More information about the Haskell-Cafe mailing list