我尝试在非递归阶乘函数中从 6 倒数到 1,但出现编译器错误:
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
我从底部附近得到了这个想法here
已将函数更改为仅计数并且它有效,但我有兴趣知道为什么会失败。有没有更好的倒数方法?
使用VS2012更新3
最佳答案
Have changed the function to just count up and it works, but I'm interested to know why this failed.
您的示例失败,因为 ..
和 -
是两个不同的运算符,编译器需要将它们分开。您可以添加空格,而不是用括号将 -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
关于F# For 循环负数倒数 - int 类型不支持运算符..-,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17951969/