I’m used to work with functional programming (mainly Haskell) and I’m beginning with OO (scala).
I’m having troubles on translating my code. For instance, that’s my Haskell definition of a B-tree:
data BTree a =
Leaf
|Node2 (BTree a) a (BTree a)
|Node3 (BTree a) a (BTree a) a (BTree a)
deriving (Eq,Read,Show)
It’s quite simple. My tree is empty, or it has a value and is a father of two trees or it is a father of 3 sub trees.
What is it on OO? I have no clue. I just can’t figure out how can I do it in a sane way.
Since you have Scala in your tag-list, here is how it would be done in Scala:
You have a base trait (in Haskell the type), and derived from that all the Haskell constructors as
caseclasses. That way you can use them in Scala pattern matching as well.In languages like Java (since 1.5), C++ and C# you have the same kind of templates to help type safety. They basically work like the type variables in Haskell.
This example is in Scala, but for other OO languages you would do it in a similar way: Create an abstract base class and turn the constructors of your data into classes/objects.