[Haskell-beginners] Problem with numeric types

David McBride toad3k at gmail.com
Sat Jul 2 06:09:27 UTC 2016


Because mod :: Integral a => a -> a -> a and sqrt :: Floating a => a -> a,
the final type of primes' ends up being :: (Floating a, Integral a) => [a],
which doesn't work very well obviously.

The easiest solution is to try
let primes' = 2 : [p | p <- odds, null [d | d <- (takeWhile (<=ceiling
(sqrt (fromInteger p))) odds), p `mod` d == 0]]

You can make your own sqrt if you want to clean it up.
let isqrt = ceiling . sqrt . fromInteger


On Fri, Jul 1, 2016 at 9:41 PM, Russ Abbott <russ.abbott at gmail.com> wrote:

> I'm trying to define primes using just list comprehension.  The following
> works.
>
> Prelude> odds = [3, 5..]
>
> Prelude> primes = 2 : [p | p <- odds, null [d | d <- take (p `div` 4)
> odds, p `mod` d == 0]]
>
>
> But when I replace  "take (p `div` 4)"   with    takeWhile (<=(sqrt p))
>  as in
>
> Prelude> primes' = 2 : [p | p <- odds, null [d | d <- (takeWhile (<=(sqrt
> p)) odds), p `mod` d == 0]]
>
> I get no error message on entering the statement, but when I run
>
> Prelude> take 8 primes'
>
> I get an error message that I can't understand.
>
> <interactive>:23:1: error:
>     • Ambiguous type variable ‘a0’ arising from a use of ‘it’
>       prevents the constraint ‘(Floating a0)’ from being solved.
>       Probable fix: use a type annotation to specify what ‘a0’ should be.
>       These potential instances exist:
>         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
>
> I tried using (ceiling (sqrt p)), and I tried to explicitly declare it an
> Int, but neither of those helped.
>
> I'd appreciate some help.
>
> Thanks.
>
> P.S. The following runs fine.
>
> Prelude> takeWhile (<= (sqrt 99)) odds
>
> So I'm completely stumped.
>
>
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20160702/68226c2e/attachment.html>


More information about the Beginners mailing list