[Haskell-cafe] Datatypes - Haskell

Sebastian Sylvan sebastian.sylvan at gmail.com
Sat Feb 9 19:52:10 EST 2008


On Feb 10, 2008 12:09 AM, Mattes Simeon <simeon.mattes at gmail.com> wrote:

> Hello to everybody
>
> I am an new user of Haskel and generally in functional programming and I
> could
> say that I am very impressed from this Language. Though I can't understand
> the
> use of datatypes.
>
> Let's take a firly simple situtation
>
> e.g. data Pair a b = Pair a b
>
> i.e. an new type with name Pair parameterized over the types a,b with one
> Constructor named Paid which take two values of type a,b
>
> a more complex one would be
> data Either a b = Left a | Right b
>
> i.e a new type named Either parameterized over the types a, b and two
> Constructors 1. Left which take one value of type a and 2. Right which
> takes one
> value of type b
>
> I consider that the definitions above are well formulated. Nevertheless I
> can't
> understand them quite well.
>
> I have read that datatypes are used to define new structures. So, is there
> any
> corresponding example in C, sinch I am quite familiar with structures in
> it? I
> hope the word C here is allowed here :o)
>

I guess C++ would be closer...

template< class A, class B>
struct Pair
{
    A fst;
    B snd;
}

template< class A, class B>
struct Either
{
    enum {Left, Right} tag;
    union{
       A left;
       B right;
   };
}

In the second example the tag would be used to figure out which of the two
alternatives the structure actually is. In Haskell you can just pattern
match on the constructor.

-- 
Sebastian Sylvan
+44(0)7857-300802
UIN: 44640862
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20080210/c3fc18eb/attachment.htm


More information about the Haskell-Cafe mailing list