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

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

    Consider this somewhat equivalent of Maybe in C++/Java'ish psuedocode...

    template
    abstract class Maybe { ... }
    
    template
    class Just : Maybe {
        // constructor
        Just (T val) { ... }
    
        ...
    }
    
    template
    class Nothing : Maybe {
        // constructor
        Nothing () { ... }
    
        ...
    }
    

    That is not specific to Maybe, it can be applied to any ADT. Now what exactly will

    data Maybe a = a | Nothing
    

    model into ? (assuming that its legal syntax).

    If you were to write a switch statement, to 'pattern match' against types, what will u match against (the switch is on the TYPE not the value), something like this (not necessarily valid code) :

    switch (typeof (x)) {
        case Just : ...
        case Nothing : ...
        default : ... // Here you dont have any 'a' to get the inner type
    }
    

提交回复
热议问题