Why do Maybe/Optional types use a Just/Some type instead of the actual type?

前端 未结 6 584
日久生厌
日久生厌 2020-12-19 02:16

In Idris, the Maybe type is defined as followed:

data Maybe a = Just a | Nothing  

It\'s defined similarly in Haskell:

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-19 02:52

    I am not sure it is correct to speak of "benefits" in this context. What you have here is just a consequence of the way types are implemented in Haskell and ML - basically, Hindley-Milner algebraic type system. This type system essentially assumes that every value belongs to a single type (putting aside Haskell's numeric tower and bottom, which are outside of this discussion.) In other words, there is no subtyping, and that's for a reason - otherwise the type inference would be undecidable.

    When you define type Maybe a what you want is to adjoin a single additional value to the type denoted by a. But you can't do it directly - if you could then every value of a would belong to two different types - the original a and Maybe a. Instead, what is done is a is embedded in a new type - you have a canonical injection a -> Just a. In other words, Maybe a is isomorphic to a union of a and Nothing which you can't represent directly in HM type system.

    So I don't think that arguments along the lines that such a distinction is beneficial are valid - you can't have a system without it which is still ML or Haskell or any familiar HM-based system.

提交回复
热议问题