In Haskell I have the following
data Box a = Box a deriving Show
instance Functor Box where
fmap func (Box a) = Box (func a)
box :: Box Int
box = Box 8
wrapped :: Box (Box Int)
wrapped = Box <$> box
unwrap :: (Box a) -> a
unwrap (Box val) = val
In GHCi I can call fmap
with unwrap wrapped
and I get Box 8
, which I would expected.
*Main> fmap unwrap wrapped
Box 8
When I call fmap
with unwrap box
I get error about the types not matching, but I was thinking I would get the value 8.
*Main> fmap unwrap box
<interactive>:26:13: error:
• Couldn't match type ‘Int’ with ‘Box b’
Expected type: Box (Box b)
Actual type: Box Int
• In the second argument of ‘fmap’, namely ‘box’
In the expression: fmap unwrap box
In an equation for ‘it’: it = fmap unwrap box
• Relevant bindings include
it :: Box b (bound at <interactive>:26:1)
I would have expected fmap unwrap box
would give the value 8
.
How would I define unwrap
to be able to get the value of Box 8
for wrapped
and 8
for box
when using fmap
?
I do not think it matters but I am using GHCi version 8.8.4
If you have a box = Box 8
and want to get a plain 8
, you should just call unwrap box
, not fmap unwrap box
. In general, fmap
will never let you unwrap a value because its type (Functor f) => (a -> b) -> fa -> fb
specifies that the result of fmap xy
will have the wrapped type fb
. Let's walk through the types to see why this happens:
When we call fmap unwrap
, we can "unify" the type of unwrap
with the type of the first argument to fmap
, which gives us this specialized type for fmap
:
fmap :: (Functor f) => (a -> b) -> f a -> f b
unwrap :: Box a -> a
fmap :: (Functor f) => (Box a -> a) -> f (Box a) -> f a
Notice that because f
doesn't appear in the type of the first argument of fmap
, Box
doesn't fill in for f
. We can then apply unwrap
to this specialized version of fmap
:
fmap unwrap :: (Functor f) => f (Box a) -> f a
This is almost certainly not the type you're expecting here. When we unify this for the argument Box (Box 8)
, we get the specialized type:
fmap unwrap :: (Functor f) => f (Box a ) -> f a
Box (Box 8) :: Box (Box Int)
fmap unwrap :: Box (Box Int) -> Box Int
But when we try to unify this with the type of argument Box 8
, we run into a problem:
fmap unwrap :: (Functor f) => f (Box a) -> f a
Box 8 :: Box Int
I can't match the type of Box 8
with the expected argument to fmap unwrap
because Int
doesn't match the type Box a
.
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.