Reputation: 333
I have recently started diving into Haskell. Its quite interesting, but the definition of Nothing
baffles me and is not sinking in. On GHCI
Prelude> :t Nothing
Nothing :: Maybe a
Shouldn't Nothing
be Just Nothing
, why Maybe a
?
Upvotes: 3
Views: 1554
Reputation: 53705
Consider Scala, which has subtyping. Its equivalent to Nothing
is called None
. None
has type None
, which is a subtype of Option[a]
. Scala's equivalent to Just
is Some(foo)
, which has type Some[Foo]
, which is a subtype of Option[Foo]
. Haskell does not have subtyping, and therefore types both of them as their common supertype, since this is the most useful typing for them.
Upvotes: 1
Reputation: 1307
Here is the definition of the Maybe
type:
data Maybe a = Nothing | Just a
This states that for some type a
, the type Maybe a
has two constructors: Nothing
and Just a
(a
being the same type variable that Maybe
is applied to on the LHS).
Hopefully it's clear how Just "foo"
has type Maybe String
and Just 'c'
has type Maybe Char
. But what type is Nothing
? Since Nothing
doesn't contain any value, its constructor doesn't use the a
type variable, and therefore there's nothing that constrains its type to a particular form of Maybe
.
That makes it a "polymorphic constant". Nothing
can be used in a context in which any Maybe
type is expected, because it works equally well in all of them. That's why GHCi reports its type as simply Maybe a
: the a
is a variable which could represent any type, and which type it refers to will be determined by inference based on the context in which the Nothing
value is used. But when you give Nothing
by itself, there are no additional clues 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
.
Upvotes: 19
Reputation: 5594
Maybe
is defined as
data Maybe a = Nothing | Just a
So it can either be Nothing
or Just a
. Mayba a
is the type and Nothing
and Just a
are value constructors. Just Nothing
would be a maybe wrapped inside a maybe, i.e. Maybe (Maybe a)
.
Upvotes: 4
Reputation: 183968
Maybe
is defined
data Maybe a = Nothing | Just a
so Nothing
is a (parameterless) value constructor of the type Maybe a
, for all a
, and the value it denotes can belong to all types Maybe a
, be they Maybe Bool
, Maybe [IO (Int,Char)]
or whatever a
is instantiated with.
Upvotes: 6