Question

I'm an absolute beginner with Haskell and I'm trying to build a list comprehension that generates prime numbers. I get an error with I try to call my function. I am really not sure what is causing the error. Can anyone explain what the problem is in terms an absolute beginner would understand? I am only at the basics of the Haskell typesystem.

Code:

roundupsqrt x = ceiling (sqrt x)

listnthprimes x = take x [y|y<-[1..], odd y, all (/=0) (map (y`mod`) [2..(roundupsqrt y)])]

Error:

No instance for (RealFrac a0) arising from a use of `listnthprimes'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
  instance RealFrac Double -- Defined in `GHC.Float'
  instance RealFrac Float -- Defined in `GHC.Float'
  instance Integral a => RealFrac (GHC.Real.Ratio a)
    -- Defined in `GHC.Real'
In the expression: listnthprimes 6
In an equation for `it': it = listnthprimes 6
Was it helpful?

Solution

sqrt is defined as Floating a => a -> a; you’re passing it an integer. fromIntegral would work:

roundupsqrt x = ceiling (sqrt (fromIntegral x))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top