2013-07-30 12 views
5

アム非再帰的階乗関数でダウン6から1までカウントするようにしようとコンパイラのエラーを取得:のF# - 型int演算子をサポートしていません..-

let fact x = 
    let mutable product = 1 
    for i in x..-1..1 do 
     product <- product * i 
    product 

// Error on the 6 - type 'int' does not support the operator '..-' 
let answer = fact 6 
printfn "%i" answer 

Iこのアイデアを底辺の近くから得ましたhere

機能を変更してカウントアップしても機能しましたが、なぜこれが失敗したのか分かりません。カウントダウンするより良い方法はありますか? VS2012のアップデートを3

答えて

17

Have changed the function to just count up and it works, but I'm interested to know why this failed.

..-は、2つの異なる演算子であるので、あなたの例では、失敗し、コンパイラは、それらの間の分離を必要とします。代わりに括弧で-1をラップで、あなたは、スペースを追加することができます。

let fact x = 
    let mutable product = 1 
    for i in x .. -1 .. 1 do 
     product <- product * i 
    product 

Is there a better way to count down?

あまり知られてfor .. downto .. do構築物は、ここで使用する方が適切です。

let fact x = 
    let mutable product = 1 
    for i = x downto 1 do 
     product <- product * i 
    product 
4

を使用して

は、ブラケットを使用してみてください:

... 
for i in x..(-1)..1 do 
... 
8

これは動作します:

let fact x = 
    let mutable product = 1 
    for i in x..(-1)..1 do 
    product <- product * i 
    product 

この(問題のリンクに使用されるような)いたよう:

let fact x = 
    let mutable product = 1 
    for i in x .. -1 .. 1 do 
    product <- product * i 
    product 

PS:n階乗を計算するためのより機能的な方法があります(可変変数を使うのが悪い)。最も明白な使用して再帰:

let rec fact x = 
    if x > 2 
    then x * (fact (x - 1)) 
    else x 

またはワンライナーのリストを使用して:

let fact x = [2..x] |> List.reduce (*) 
+0

多くのおかげで、特により再帰的な方法に感謝します。面白いアプローチのために私はパッドにポイントを与えた。私もあなたにポイントを与えることができれば私は(そして誰も答えた)! –

関連する問題