[Haskell-cafe] Re: OOP'er with (hopefully) trivial questions.....

Sebastian Sylvan sebastian.sylvan at gmail.com
Mon Dec 17 08:35:54 EST 2007


On Dec 17, 2007 1:18 PM, Nicholls, Mark <Nicholls.Mark at mtvne.com> wrote:
> Not really with this...
>
> The open case (as in OO) seems to be more like the Haskell class
> construct, i.e. if new types declare themselves to be members of a class
> then they must satisfy certain constaints....I can then specify "equals"
> with the class and leave the onus on the implementor to implement
> it....the data construct seems more analogous to a OO class
> definition...which is closed in the same way.

Yes that's pretty much true. In lots of cases you do have tons of
different representations of a specific type that is known at to be
closed. E.g. singly linked list has two cases it's either a "Link" or
it's the end of the list:

data List a = Link a (List a) | Nil

You could do this in C++ with two different classes inheriting from a
common base class, and then use RTTI to discover what variant of
"List" something is, or add a virtual function called "isLink" or
something, or maybe just have a single variant but add a boolean or an
enum field describing wether or not the "Link" pointer is valid. As
you see it gets messy (and in this trivial case you would use the
"built in" two-way case of pointers, where you can specify "Nil" as
simply a link with a null "tail" - but that's not always the possible,
and even in this case I find it much nicer to explicitly use two
completely different representations for the two variants).

In general you don't tend to use this sort of tagged union to build
stuff in OOP so there's no direct correspondence to "typical" OOP
patterns.

So one side effect of learning Haskell is (or at least was to me) a
greater familiarity with that approach to describing data, which is
simple and powerful enough that you sometimes emulate it even when it
gets a bit messy in other languages. It really gets nice when you
start defining functions on the data type using pattern matching, as
everything is just extremely clear and nice since you only deal with
one case at a time.. Here's a few examples using the list
(uncompiled):


isEmpty Nil = True
isEmpty _ = False

length Nil = 0
length (Link _ xs) = 1 + length xs

concat Nil xs = xs
concat (Link x xs) ys = Link x (concat xs ys)


-- 
Sebastian Sylvan
+44(0)7857-300802
UIN: 44640862


More information about the Haskell-Cafe mailing list