繁体   English   中英

F#返回一个布尔值

[英]F# Returning a Boolean

第一次在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正如我强迫函数返回bigints(必须有一个更好的方法,但一次一步)....

编辑 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

你可以用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) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM