I'm working through Project Euler, and a lot of problems involve similar functions, for example calculating lists of primes. I know calculations with Integer are slower than Int so I'd like to write the functions to work with both, depending on the size of the numbers I'm working with.
module Primes
(
isPrime
,prime
,allPrimes
)
where
import Data.List
isPrime :: Int -> Bool
isPrime n
| n == 0 = False
| n == 1 = False
| n < 0 = isPrime (-n)
| n < 4 = True
| n `mod` 2 == 0 = False
| n `mod` 3 == 0 = False
| any ( (==0) . mod n ) [5..h] = False
| otherwise = True
where
h = ( ceiling . sqrt . fromIntegral ) n
allPrimes :: [Int]
allPrimes = [ x | x<- [2..], isPrime x ]
prime :: Int -> Int
prime n = allPrimes !! (n-1)
I know this code isn't generally as optimal as it could be. I'm just interested in how to make the integer types more generic.
Try Integral
it should allow support for both Int
and Integer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With