我目前在研究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)
请注意,这次在derv1函数中我使用了dx
。我对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'