[Haskell-beginners] Equivalent of inheritance in Haskell

Antoine Latter aslatter at gmail.com
Tue Dec 14 05:09:25 CET 2010


On Mon, Dec 13, 2010 at 9:10 PM, C K Kashyap <ckkashyap at gmail.com> wrote:
>>
>> But there is not a way to easily say (in Haskell) "type A is
>> everything that type B is plus these other things here ...". Haskell
>> is not an OO language.
>
> This captures what I had in mind. Using compound types seems ok but
> I'd still need to do some mechanical stuff if I had to provide a
> function that works on the compound type which is actually defined for
> a component type.
>
> If I understand you right .. you'd build a 'Man' type and 'Woman' type
> by using a 'Person' type. Lets say, there is a function called getName
> that is Person -> String
> I'd have to mechanically define a function getName :: Man -> String -
> that extracts the person inside and calls getName on it - did I
> understand it right?
> Or would you typically write extract functions that'll return the
> components and then the user could call the method on the component?
> As in .... getPerson :: Man -> Person ... then call getName on that.
>
> How do you deal with situations like that?
>

Well, in this case I might just have a person type with a 'gender'
field :-) Then I get the polymorphism and code-reuse for free!

But what you're talking about is something that OO-style programming
is particularly aligned towards, and functional programming generally
is not.

One thing people do is use type-classes - this would be a bit like
having 'Car' and 'Truck' implement the same interface. The simple
building blocks would be duplicated, but the complex application-level
functionality could be written against the typeclass.

Another approach is with functional lenses - these are libraries that
aim to make updating complex compound types easier. Off the top of my
head I know of fclabels[1], but I know there are others. If you're
interested in this approach you might be able to email the -cafe
mailing list to ask for more.

Is there a particular problem you're trying to solve? we might be able
to take the conversation in a less speculative direction.

Antoine

[1] http://hackage.haskell.org/package/fclabels



More information about the Beginners mailing list