簡體   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