以下代码旨在生成Double或Integer。假设s
为negate
或id
; 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
是多态的这一事实。这里发生了什么,我该如何解决?
答案 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)