What is the type of Nothing in Haskell?

后端 未结 5 986
北恋
北恋 2021-01-01 10:51

I\'m at page 118 of the book \"Learn You a Haskell for Great Good!\"

It is written there:

ghci> :t Nothing 
Nothing :: Maybe a

H

5条回答
  •  温柔的废话
    2021-01-01 11:39

    The Maybe type has two constructors: Nothing and Just a, where a is a type variable. Nothing itself does not determine (constrain) the type, but in any reasonable context you'll find something like (I do not claim it to be syntactically correct Haskell but something I would have written 10 years ago):

    if (foo == 5)
    then Nothing
    else Just 5
    

    And then type inference will tell you that (assume 5 was an argument to this code snippet 'foo' of type Int) that foo has type:

    foo :: Int -> Maybe Int
    

    But as the previous poster pointed out, Maybe a is a perfectly good type. You'll find the same non-issue with [] ie the list type with [] (the constructor for an empty list).

提交回复
热议问题