gpt4 book ai didi

Haskell 类型错误 : Inferred type is less polymorphic than expected

转载 作者:行者123 更新时间:2023-12-04 06:22:19 24 4
gpt4 key购买 nike

我现在正在与 Haskell 混在一起,对于我的一生,我无法弄清楚为什么以下内容有效......

square :: (Num a) => a -> a 
square x = x * x
dx = 0.0000001
deriv1 :: (Fractional a) => (a -> a) -> (a -> a)
deriv1 g = (\x -> ((g (x + 2) - (g x)) / 0.0000001 ))
main = printf "res==%g %g\n" (square 5.12::Double) ((deriv1 square) 2::Float)

但这并没有......
square :: (Num a) => a -> a 
square x = x * x
dx = 0.0000001
deriv1 :: (Fractional a) => (a -> a) -> (a -> a)
deriv1 g = (\x -> ((g (x + 2) - (g x)) / dx ))
main = printf "res==%g %g\n" (square 5.12::Double) ((deriv1 square) 2::Float)

注意我用过 dx这次在derv1函数中。我是 Haskell 的新手,所以任何关于类型的深入讨论都可能很快从我身边溜走,我会死的旋转。我必须有一些类似于命令式答案的东西,否则在我的 Haskell 职业生涯早期,它几乎肯定会丢失。

我收到的错误消息是:
Inferred type is less polymorphic than expected
Quantified type variable `a' is mentioned in the environment:
dx :: a (bound at sicp-1.40.hs:12:0)
When trying to generalise the type inferred for `deriv1'
Signature type: forall a. (Fractional a) => (a -> a) -> a -> a
Type to generalise: (a -> a) -> a -> a
In the type signature for `deriv1'
When generalising the type(s) for `deriv1'

最佳答案

您收到错误是因为 monomorphism restriction .由于您没有为 dx 提供类型签名它最终推断为 Double在这种情况下。你可以给出一个明确的、多态的签名,比如

dx :: Fractional a => a
dx = 0.0000001

或者您可以通过在源文件顶部包含此行来禁用单态限制
{-# LANGUAGE NoMonomorphismRestriction #-}

关于Haskell 类型错误 : Inferred type is less polymorphic than expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11590180/

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