Peter Hall
Peter Hall

Reputation: 58785

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.

Upvotes: 5

Views: 171

Answers (2)

hugomg
hugomg

Reputation: 69954

A more general solution to this kind of problem, you could try getting your code to compile without the explicit type declarations. Haskell will assume the most general type possible and you can find out what it was by, for example, loading your file on GHCi and doing a :t myFunctionName

Upvotes: 7

Joshua Rodgers
Joshua Rodgers

Reputation: 5404

Try Integral it should allow support for both Int and Integer

Upvotes: 7

Related Questions