Reputation: 31918
I have almost been able to create a valid functor instance for the type Pair. Problem is, Pair takes two arguments both of the same type, so when I write
fmap f (Pair a a') = Pair a (f a')
I cannot guarantee that the result is a valid Pair, since (f a') might be any type.
What is the Haskell way of ensuring this constraint?
import Test.QuickCheck
import Test.QuickCheck.Function
data Pair a = Pair a a deriving (Eq, Show)
instance Functor Pair where
fmap f (Pair a a') = Pair a (f a')
-- stuff below just related to quickchecking that functor instance is valid
main = quickCheck (functorCompose' :: PFC)
type P2P = Fun Int Int
type PFC = (Pair Int) -> P2P -> P2P -> Bool
instance (Arbitrary a) => Arbitrary (Pair a) where
arbitrary = do
a <- arbitrary
b <- arbitrary
return (Pair a b)
functorIdentity :: (Functor f, Eq (f a)) => f a -> Bool
functorIdentity f = fmap id f == f
functorCompose :: (Eq (f c), Functor f) => (a -> b) -> (b -> c) -> f a -> Bool
functorCompose f g x = (fmap g (fmap f x)) == (fmap (g . f) x)
functorCompose' :: (Eq (f c), Functor f) => f a -> Fun a b -> Fun b c -> Bool
functorCompose' x (Fun _ f) (Fun _ g) = (fmap (g . f) x) == (fmap g . fmap f $ x)
Here is the error message I get, btw:
chap16/functor_pair.hs:22:29: Couldn't match expected type ‘b’ with actual type ‘a’ …
‘a’ is a rigid type variable bound by
the type signature for fmap :: (a -> b) -> Pair a -> Pair b
at /Users/ebs/code/haskell/book/chap16/functor_pair.hs:22:3
‘b’ is a rigid type variable bound by
the type signature for fmap :: (a -> b) -> Pair a -> Pair b
at /Users/ebs/code/haskell/book/chap16/functor_pair.hs:22:3
Relevant bindings include
a' :: a
(bound at /Users/ebs/code/haskell/book/chap16/functor_pair.hs:22:18)
a :: a
(bound at /Users/ebs/code/haskell/book/chap16/functor_pair.hs:22:16)
f :: a -> b
(bound at /Users/ebs/code/haskell/book/chap16/functor_pair.hs:22:8)
fmap :: (a -> b) -> Pair a -> Pair b
(bound at /Users/ebs/code/haskell/book/chap16/functor_pair.hs:22:3)
In the first argument of ‘Pair’, namely ‘a’
In the expression: Pair a (f a')
Compilation failed.
(This is an exercise from http://haskellbook.com/)
Upvotes: 0
Views: 249
Reputation: 116139
Assume f :: t1 -> t2
. We want fmap f :: Pair t1 -> Pair t2
. Your attempt was:
fmap f (Pair a a') = Pair a (f a')
-- ^
which is ill-typed because a
is of type t1
instead of type t2
.
If only we had something that can transform t1
values into t2
values, we could simply use it on a
and everything would type check. Do we have such a thing? ;-)
Upvotes: 2