In the chapter 14 of Real World Haskell (Monads) , the type signature of the inject function return
is return :: a -> ma
, where ma
is a type constructor, so under ghci I can specify a type signature for a return arg1
, such as:
*Main> return 1 :: Maybe Integer
Just 1
*Main> return "ok" :: Maybe String
Just "ok"
Because Nothing
is the value of the type Maybe a
, Nothing
's type is Maybe Integer
or Maybe String
, so I think I can specify the type as follows:
*Main> return Nothing :: Maybe String
But I got an error:
Couldn't match type `Maybe a0' with `[Char]'
Expected type: String
Actual type: Maybe a0
In the first argument of `return', namely `Nothing'
In the expression: return Nothing :: Maybe String
In an equation for `it': it = return Nothing :: Maybe String
I am confused about what is the type signature for that.
In the lines
return 1
return "ok"
the return
works inside the Maybe
monad, so return = Just
here.
In the line
return Nothing :: Maybe String
the compiler spots that your code is of the form
return ... :: Maybe ...
so, once again, return = Just
. Your code is equivalent to
Just Nothing :: Maybe String
which is the same as
Just (Nothing :: String)
but Nothing
is not a string, it is a Maybe a
for any a
-- hence the type error.
You probably are looking for
Nothing :: Maybe String -- no return here
which works fine.
By the way, you can ask GHCi to give the type for an expression with the :t
command:
> :t return Nothing
Monad m => m (Maybe a)
The difference between:
*Main> return 1 :: Maybe Integer
And
*Main> return Nothing :: Maybe String
Is that 1
has type Integer
, but Nothing
has type Maybe a
. If you want to wrap Nothing
into another Maybe
value, you should specify the type for Nothing
like this:
*Main> return Nothing :: Maybe (Maybe String)
Just Nothing
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.