Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write these functions to be independent of choice of type: Int vs Integer

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.

like image 336
Peter Hall Avatar asked Sep 04 '11 22:09

Peter Hall


1 Answers

Try Integral it should allow support for both Int and Integer

like image 97
Joshua Rodgers Avatar answered Nov 03 '22 01:11

Joshua Rodgers