0

I just write a simple code in Haskell,

coo x y = ((lim-1)*y*(y-1)`div`2) + (y*(y-1)*(sum (map (\j->(x`div`j)-j)  [2..lim] )))
  where
    lim = floor (sqrt x)

but when I use 'coo 10 10' in ghci, it gives me the following error:

<interactive>:3:1:
No instance for (Floating a0) arising from a use of ‘it’
The type variable ‘a0’ is ambiguous
Note: there are several potential instances:
  instance Floating Double -- Defined in ‘GHC.Float’
  instance Floating Float -- Defined in ‘GHC.Float’
In the first argument of ‘print’, namely ‘it’
In a stmt of an interactive GHCi command: print it

What happened? I am kind of sure I match all types correct.

4
  • You're going to need an explicit type signature for (or within) coo 10 10 itself. To see why, type :t coo in GHCi. The types are correct, but coo 10 10 is still polymorphic. You'll have to specify whether you want coo 10 10 :: Float or coo 10 10 :: Double. Commented Apr 1, 2016 at 8:10
  • @Rhymoid nope ... although the error would indicate this it is not the problem here - try it: you will just get another error (telling you Float or Double is not Integral) Commented Apr 1, 2016 at 8:10
  • sqrt :: Floating a => a -> a; you can use sqrt (fromIntegral x), but be careful of precision loss. Commented Apr 1, 2016 at 8:11
  • @Carsten I agree it's not a complete answer, but it is an answer for the immediate problem. Learning how to debug is vital in learning a language. Commented Apr 1, 2016 at 8:14

1 Answer 1

4

If you look closely (or ask GHCi) you will see that your function has the type

coo :: (Floating a, Integral a, RealFrac a) => a -> a -> a

telling GHC to use some type a that is both a Floating and a Integral and this will get difficult (there are no such types in the Prelude)


I am not 100% sure what you are trying to do but one way to fix this is to change lim into:

lim = floor (sqrt $ fromIntegral x)

this will yield

λ> coo 10 10
360
Sign up to request clarification or add additional context in comments.

4 Comments

Could you suggest how to fix this problem?
done - but I don't know what your function is supposed to be doing
The proper way would be to implement the integer square root function.
@Rhymoid sure but this was not the question here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.