Comment

Comment by ekidd

Haskell doesn't really do inheritance, unless you somehow get O'Haskell to work on a modern machine.

In place of inheritance, you have two mechanisms: algebraic data types and type classes. They work great for many programs, but neither of them is an exact fit for Java-style object-oriented programming.

An algebraic data type has a name ("Bool", in the first example below), and several constructors ("True" and "False"). Constructors can take positional and named arguments, and they can take type parameters:

    data Bool = True | False
    data Shape =
        Square { l :: Int, t :: Int, w :: Int, h :: Int }
      | Circle Int Int Int
    data Maybe a = Just a | Nothing
Once you define an algebraic data type, you can't add new constructors. But you can write functions which match against the existing constructors at runtime, giving you a form of runtime dispatch vaguely analogous to method lookup:

    boolToString :: Bool -> String
    boolToString True = "true"
    boolToString False = "false"
So algebraic data types work great if you have one abstract interface with known set of concrete subclasses. It's a really great way to think about complex data structures with multiple types of nodes.

A type class is a little bit like a C++ template protocol: It says that a given type implements a set of functions. But as with C++ templates, it's effectively resolved at compile time. (Well, the implementation is quite a bit different, but that's the rough idea.)

Now, ADTs and type classes are great. But if you find yourself using crazy hacks to recreate an OO class hierarchy in Haskell, you're probably fighting against the language. Either structure your program differently, or find a different language.

parent ekidd 15 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton