模式匹配后失去多态性

时间:2012-05-23 22:45:09

标签: haskell polymorphism pattern-matching

以下代码旨在生成Double或Integer。假设snegateid; n整个部分;和f小数部分或Nothing表示整数。

computeValue :: Num a => (a->a) -> Integer -> (Maybe Double) -> Either Double Integer
computeValue s n Nothing = Right $ s n
computeValue s n (Just a) = Left $ s (fromIntegral n + a)

当我编译它时,我得到:

test1.hs:2:28:
    Couldn't match type `Integer' with `Double'
    Expected type: Either Double Integer
      Actual type: Either Double a
    In the expression: Right $ s n
    In an equation for `computeValue':
        computeValue s n Nothing = Right $ s n

test1.hs:2:38:
    Couldn't match type `Integer' with `Double'
    In the first argument of `s', namely `n'
    In the second argument of `($)', namely `s n'
    In the expression: Right $ s n

似乎某种程度上编译器已经忘记了s是多态的这一事实。这里发生了什么,我该如何解决?

1 个答案:

答案 0 :(得分:10)

s不是来自函数内部的多态:你可以使用任何在某些 Num实例上运行的函数作为此参数,它可能只是一个函数适用于Complex!您需要的是一个普遍量化的函数s,即实际上可以使用任何 Num实例调用的函数。

{-# LANGUAGE Rank2Types #-}

computeValue :: (forall a . Num a => a->a) -> Integer -> Maybe Double -> Either Double Integer
computeValue s n Nothing = Right $ s n
computeValue s n (Just a) = Left $ s (fromIntegral n + a)

然后就可以了:

Prelude Data.Either> computeValue id 3 Nothing
Right 3
Prelude Data.Either> computeValue negate 57 (Just pi)
Left (-60.1415926535898)