0

I have a function written in F# which determines if a number is prime or not

let rec isPrime (number, f):bool =
    match number, f with
    | n, f when f = 1 || f = 0 -> isPrime(number, (f + 1)) 
    | n, f when f > n / 2 -> true
    | n, f when n % f = 0 -> false
    | n, f when n % f > 0 -> isPrime(number, (f + 1))
    | _ -> false

printfn "%b" (isPrime (7, 0))

This function to me is really nice clean F# code, sure the algorithm may not be perfect but it works and looks nice. But here's the problem, what if I wanted to use a number bigger than the int type will allow?

let rec isPrime (number:uint64, f:uint64):bool =
    match number, f with
    | n, f when f = 1UL || f = 0UL -> isPrime(number, (f + 1UL))
    | n, f when f > n / 2UL -> true
    | n, f when n % f = 0UL -> false
    | n, f when n % f > 0UL -> isPrime(number, (f + 1UL))
    | _ -> false

printfn "%b" (isPrime (7UL, 0UL))

I've had to liter my code with types, this isn't as clean as I would like. Is there some way to avoid explicitly mentioning the uint64 type?

JordanW
  • 121
  • 1
  • 3
  • 2
    For one thing, your annotations on the function arguments are unnecessary, since the comparisons to appropriately typed literals constrain their types. See the answers to http://stackoverflow.com/questions/4732672/how-to-write-a-function-for-generic-numbers for more ideas. – kvb Dec 04 '14 at 03:13
  • Marked as duplicate: the two answers give you the two approaches you can use to avoid hardcoding types and making this work for any integral type. – Richard Dec 04 '14 at 08:32

0 Answers0