Haskell ambiguous type

485 Views Asked by At
findMult lst n = [x | x <- lst, x `mod` n == 0]

primes num = 
    let n = [2..num]
        x = ceiling (sqrt num)
        nsqrt = [2..x]
        not_prime = map (findMult n) nsqrt
    in diff2 n (concat not_prime)   

has the following problem when i try to run it

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

I tried using fromIntegral but i don't think i used correctly as that gives me compilation error. Please help.

The purpose of this is to find all the prime numbers up until num.

2

There are 2 best solutions below

0
On BEST ANSWER

You get error messages like this when you use an integral value where a floating value was expected (or vice versa).

In this case the problem is that you're calling sqrt, which takes a floating point value as an argument, on num making the compiler think num is a floating point value. But also use num as an upper limit for n, which is a list of integral values (because it's used as an argument to findMult which needs a list of integral values).

So before calling sqrt on num call fromIntegral on it, like this:

x = ceiling (sqrt (fromIntegral num))
0
On

Instead of taking the square root, you can take all squares up to the limit.

-- instead of
{- x = ceiling (sqrt num)
   nsqrt = [2..x] -}
-- avoid sqrt
nsqrt = takeWhile (\x -> (x-1)^2 < num) [2..]
-- or even avoid multiplication altogether
nsqrt = map fst . takeWhile ((< num) . snd) . zip [2..] $ scanl1 (+) [1,3..]