2013-05-17 20 views
1

我剛剛開始使用F#並嘗試了問題歐拉問題#3。要查找的素數,我想出了下面的代碼來計算所有素數最多數量:這個函數爲什麼說「只有簡單的變量模式可以綁定在'let rec'結構中」?

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 

不幸的是,這給出了錯誤:

Only simple variable patterns can be bound in 'let rec' constructs

爲什麼會出現這個錯誤?

回答

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 

這不適用於遞歸函數。

+0

哦......對! woops :) – KallDrexx

相關問題