Confusion over Haskell's "Nothing"
Here is the type definition Maybe
:
data Maybe a = Nothing | Just a
This means that for some type, a a
type Maybe a
has two constructors: Nothing
and Just a
( a
is a variable of the same type that Maybe
applies to LHS).
Hopefully this is clear how Just "foo"
has a type Maybe String
and Just 'c'
has a type Maybe Char
. But what type Nothing
? Since it Nothing
does not contain any value, its constructor does not use a type variable a
, and therefore there is nothing that restricts its type to a specific form Maybe
.
This makes it a "polymorphic constant". Nothing
can be used in a context in which any type is expected Maybe
, because it works equally well in all of them. This is why GHCi communicates its type as simply Maybe a
: a
is a variable that can represent any type, and which type it refers to will be inferred based on the context in which the value is used Nothing
. But when you give Nothing
by itself, there is no additional clue about its specific type, so you just see the variable.
> :t Nothing
Nothing :: Maybe a
> :t (Nothing :: Maybe Int)
(Nothing :: Maybe Int) :: Maybe Int
> :t (Nothing :: Maybe Char)
(Nothing :: Maybe Char) :: Maybe Char
And by the way Just Nothing :: Maybe (Maybe a)
; it's a Maybe
wrapped in another Maybe
.
source to share
Consider a Scala that has subtyping. Its equivalent Nothing
is called None
. None
has a type None
that is a subtype Option[a]
. Scala's equivalent Just
is Some(foo)
, which has a type Some[Foo]
that is a subtype Option[Foo]
. Haskell is not subtyped and therefore displays both of them as its common supertype, as this is the most useful printing for them.
source to share