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

前端 未结 6 583
日久生厌
日久生厌 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:40

    The benefit of the constructor (Just or Some) is that it provides a way to distinguish between the branches of the data type. That is, it avoids ambiguity.

    For example if we were relying on type inference, then the type of x in the following seems fairly straightforward — String.

    x = "Hello"
    

    However, if we allowed your definition of Maybe, how would we know whether x was String, a Maybe String or a Maybe (Maybe String) etc.

    Also consider a data type with more than two cases:

    data Tree a
      = Empty
      | Node (Tree a) (Tree a)
      | Leaf a
    

    If we simply removed the constructors (other than Empty), following your suggestion for Maybe, we'd end up with:

    data Tree a
      = Empty
      | (Tree a) (Tree a)
      | a
    

    I hope you can see that the ambiguity gets even worse.

提交回复
热议问题