Hacker News new | past | comments | ask | show | jobs | submit login

This is definitely an FP vs OO thing. If you wanted to refer to the value in an ADT you'd introduce a new type to refer to it, which in Elm would be:

    type Message 
        = IncrementBy Amount
        | DecrementBy Amount
        | Set Amount

    type Amount = Amount Int
Obviously this is a contrived example - you wouldn't bother if you were dealing with an Int but once the message gets more complicated it can make sense.



That's a different thing.

Given the above ADT, how would you write a function that prints the amount of a Message, regardless of which case it is?


You'd use a switch over the ADT and extract the values as appropriate. This is method dispatch vs function dispatch. In practice you can do the same things with either, but they reflect the focus on behaviour (OO) vs data (FP).


That's the point of my last example. By building this on subtyping, you can hoist that shared property out of the cases and up to the supertype. That lets you define state and behavior that is case independent without having to write a bunch of brain-dead matches that go over every case to extract conceptually the same field from each one.

Of course, you can also reorganize you datatype so that the shared state is hoisted out into a record that also contains a sum typed field for the non-shared stuff. But that reorganization is a breaking change to any consumers of the type.

Modeling this on top of classes and subtyping lets you make those changes without touching the user-visible API.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: