Haskell forall
Why the following function CAN NOT be compiled
liftTup :: (x -> f x) -> (a, b) -> (f a, f b)
liftTup f (t, v) = (f t, f v)
Compilation Error
The default function signature is the following
liftTup :: forall x (f :: * -> *) a b. (x -> f x) -> (a, b) -> (f a, f b)
liftTup f (t, v) = (f t, f v) ↑ ↑
| |
a ← + → x
↑
+ -> GHC treats a and x are different type
e.g f::Int -> Int
x :: Int
let a = "abc"
f a ⇒ ERROR
ERROR: Couldn't match expected type ‘x’ with actual type ‘a’
GHC treats 'x' and 'a' are different type
ERROR: Couldn't match expected type ‘x’ with actual type ‘b’
GHC treats 'x' and 'b' are different type
Rewrite the following, it should be OK.
{-# LANGUAGE RankNTypes #-}
liftTup :: (forall x. x -> f x) -> (a, b) -> (f a, f b)
liftTup f (t, v) = (f t, f v)
-- x is 'any' type
-- (forall x. x -> f x)
-- f is polymorphic function