[Haskell-cafe] Re: Datatypes - Haskell

Victor Nazarov asviraspossible at gmail.com
Sun Feb 10 08:12:10 EST 2008


On Feb 10, 2008 3:40 PM, Mattes Simeon <simeon.mattes at gmail.com> wrote:
> Thanks for your help. It was very useful.
>
> Though in comparison with C or C++ I can't figure out so clear the syntax.
> Maybe it has to do with the syntactic Sugar of each Language. I 'll give you a
> similar example I saw in a book for Haskel
>
> The following program just returns the value of the position of a datatype Tuple
> which can hold one or two elements.
>
> data Tuple a b = One a | Two a b
> tuple1 (One a)= Just a
> tuple1 (Two a b) = Just a
>
> tuple2 (One a) = Nothing
> tuple2 (Two a b) = Just b
>
> The corresponding Version in C++, which seems to be more appropriate, would be

I think this is the most native way to do it in C++:
template <class A, class B>
class Tuple {
public:
    static Tuple<A, B> *One (A *a) { return new One (a); }
    static Tuple<A, B> *Two (A *a, B *b) { return new Two (a, b); }
    virtual A *tuple1 () = 0;
    virtual B *tuple2 () = 0;
};

template <class A, class B>
class One : Tuple<A, B>
{
public:
  One (A *a) { this->a = a; }
  A *tuple1 () { return a; }
  B *tuple2 () { return NULL; }
private:
  A *a;
}

template <class A, class B>
class Two: Tuple<A, B>
{
public:
  Two (A *a, B *b) { this->a = a; this->b = b}
  A *tuple1 () { return a; }
  B *tuple2 () { return b; }
private:
  A *a;
  B *b;
}



-- 
vir
http://vir.comtv.ru/


More information about the Haskell-Cafe mailing list