gpt4 book ai didi

haskell - 模式匹配后多态性丢失

转载 作者:行者123 更新时间:2023-12-04 11:12:02 27 4
gpt4 key购买 nike

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

最佳答案

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)

关于haskell - 模式匹配后多态性丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10728897/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com