Question

The 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.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top