15 ms·
I don't know what you consider reasonable, but you can express this in Haskell with type classes and existential types: data P = forall a . Parent a => P a
by lomnakkus 13y ago
I don't know what you consider reasonable, but you can express this in Haskell with type classes and existential types:
data P = forall a . Parent a => P a
type PList = [P]
where Parent is a type class.
You have to be a bit more explicit when using a Child in the position of a Parent when adding to the list and you have to use (fully polymorphic!) pattern matches to extract elements from the list, but personally I consider this a good thing as it's more explicit.
Aside: Existential types is what OOP interfaces are -- and interfaces are often encoded as such in language semantics; see e.g. Types and Programming Languages (Pierce).
EDIT: Typos in code -- unfortunately my Haskell is a little rusty :(.
- dllthomas 13y agoYes, "Haskell can't reasonably express this with just typeclasses" is probably what I should have said. With the right extensions, Haskell can do anything, but it's not always going to be a good idea...
- lomnakkus 13y agoWhat's with the weasel words? Existential types aren't even remotely controverisial or dangerous.