1

私は F# を使い始めたばかりで、Problem Euler problem #3 を試しています。素数を見つけるために、最大数までのすべての素数を計算する次のコードを思い付きました。

let rec allPrimes foundPrimes, current, max =
    // make sure the current number isn't too high
    //   or the current number isn't divisible by any known primes
    if current >= max then
        foundPrimes
    else
        let nextValue = current + 1

        if not List.exists (fun x -> current % x = 0L) foundPrimes then
            allPrimes foundPrimes nextValue max
        else
            allPrimes (foundPrimes :: current) nextValue max 

残念ながら、これによりエラーが発生します。

'let rec' コンストラクトでバインドできるのは、単純な変数パターンのみです。

このエラーが発生するのはなぜですか?

4

1 に答える 1

5

宣言にコンマを入れたくない - 変更

let rec allPrimes foundPrimes, current, max =

let rec allPrimes foundPrimes current max =

オリジナルの正しいバージョンは

let rec allPrimes (foundPrimes, current, max) =

タプルを囲む括弧に注意してください。ただし、これには、タプル形式も使用するように再帰呼び出しを変更する必要があります。元のバージョンでは、コンパイラは次のようなことをしようとしていると考えています

let a,b,c=1,2,3

これは再帰関数では機能しません。

于 2013-05-17T00:26:09.387 に答える