Search code examples
haskelltypesprimesambiguous

Haskell ambiguous type


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.


Solution

  • 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))