Confusion over Haskell's "Nothing"

I recently started diving into Haskell. This is quite interesting, but the definition Nothing

illuminates and does not drown me. At GHCI

Prelude> :t Nothing
Nothing :: Maybe a

      

Not worth Nothing

being Just Nothing

, why Maybe a

?

+3


source to share


4 answers


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

.

+19


source


Maybe

determined

data Maybe a = Nothing | Just a

      



so Nothing

is the value to the constructor (without parameters) type Maybe a

for all a

, and the value that it represents, may belong to all types Maybe a

, whether they are Maybe Bool

, Maybe [IO (Int,Char)]

or something like a

.

+6


source


Maybe

defined as

data Maybe a = Nothing | Just a

      

So it can be Nothing

or Just a

. Mayba a

are type, and Nothing

and Just a

are value constructors. Just Nothing

maybe, maybe, wrapped inside, maybe, i.e. Maybe (Maybe a)

...

+4


source


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.

+1


source







All Articles