开发者

How can I resolve this ambiguous type variable error?

The 开发者_Go百科following code compiles just fine, but I cannot use my function:

CODE:

g :: (Fractional b, Integral b) => Int -> b -> b
g 1 x = x / (g 2 x + 1)
g 100 x = 2401*x/100
g n x = ((map (\z -> (ceiling z)^2) (1:[0.5,1..]))!!(n-1))*x / ((g (n+1) x) + fromIntegral n)

ERROR:

Ambiguous type variable `t' in the constraints:
`Integral t' arising from a use of `g' at <interactive>:1:0-6
`Fractional t' arising from a use of `g' at <interactive>:1:0-6
Probable fix: add a type signature that fixes these type variable(s)

Why is this happening, and how can I work around this? I am running GHC 6.10.4 under Windows, if that is at all relevant.

I have already taken a look at this related question, but don't think it addresses my need.


I'm not quite sure what the function is supposed to do, but your problem seems to be that you use ceiling, which has type

(RealFrac a, Integral b) => a -> b

This forces the entire result to be in the class Integral, which is probably not what you want. Adding a FromIntegral and thus changing the last line to

g n x = ((map (\z -> (fromIntegral $ ceiling z)^2) (1:[0.5,1..]))!!(n-1))*x / ((g (n+1) x) + fromIntegral n)

Makes the function compile and gives it the type

g :: (Fractional b) => Int -> b -> b
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜