在不同的上下文中使用的多态变量haskell

Xil*_*xio 4 polymorphism haskell

我有一段Haskell代码:

foo :: Num a => (a -> a) -> Either Integer Double -> Either Integer Double
foo f x = case x of
  Left i -> Left $ f i
  Right d -> Right $ f d
Run Code Online (Sandbox Code Playgroud)

它不会编译错误"无法匹配类型整数与双精度".我理解这种类型分别f计算为Integer -> IntegerDouble -> Doublein LeftRight表达式,从而产生碰撞.

如何更改此功能,以便f每次都使用正确的版本?

Yel*_*ika 6

你需要RankNTypes.

{-# LANGUAGE RankNTypes #-}

foo :: (forall a. Num a => a -> a) -> Either Integer Double -> Either Integer Double
foo f x = case x of
    Left i -> Left $ f i
    Right d -> Right $ f d
Run Code Online (Sandbox Code Playgroud)