Why are Haskell algebraic data types “closed”?

前端 未结 8 1656
终归单人心
终归单人心 2020-12-12 15:06

Correct me if I\'m wrong, but it seems like algebraic data types in Haskell are useful in many of the cases where you would use classes and inheritance in OO languages. But

8条回答
  •  抹茶落季
    2020-12-12 15:31

    First, as counterpoint to Charlie's answer, this isn't intrinsic to functional programming. OCaml has the concept of open unions or polymorphic variants, which essentially do what you want.

    As for why, I believe this choice was made for Haskell because

    • this lets types be predictable - their are only a finite number of constructors for each
    • it's easy to define your own types.
    • many Haskell functions are polymorphic, and classes let you extend custom types to fit function parameters (think Java's Interfaces).

    So if you'd rather have a data Color r b g = Red r | Blue b | Green g type, it's easy to make, and you can easily make it act like a monad or a functor or however other functions need.

提交回复
热议问题