F#返回一个布尔值

时间:2013-08-08 16:29:21

标签: f#

首先在F#中Euler #3拍摄,我想比这个可变值更优雅地返回一个布尔值。

// A number is prime if can only divide by itself and 1.  Can only be odd.
let isPrime x =
    if (x%2L = 0L) then
        false
    else
        let mutable result = true
        for i in 3L..x/2L do
            if (x%i = 0L) then
                result <- false
        result

let a = isPrime(17L)

// True
printfn "%b" a

L's正如我强迫函数返回bigint(必须有一个更好的方法,但一次只有一步)....

修改 Gradbot的解决方案

let isPrime x =
    // A prime number can't be even
    if (x%2L = 0L) then
        false
    else
        // Check for divisors (other than 1 and itself) up to half the value of the number eg for 15 will check up to 7
        let maxI = x / 2L

        let rec notDivisible i =
            // If we're reached more than the value to check then we are prime
            if i > maxI then
                true
            // Found a divisor so false
            elif x % i = 0L then
                false
            // Add 2 to the 'loop' and call again
            else
                notDivisible (i + 2L)

        // Start at 3
        notDivisible 3L

1 个答案:

答案 0 :(得分:3)

你可以用forall替换else子句:

Seq.forall (fun i -> x % i <> 0L) { 3L .. x/2L }

然后进一步将其缩小为单个表达式:

x % 2L <> 0L && Seq.forall (fun i -> x % i <> 0L) { 3L .. x/2L }

虽然我认为没有理由以不同的方式对待2,但你可以这样做:

let isPrime x = 
    { 2L .. x/2L } |> Seq.forall (fun i -> x % i <> 0L)