F# For 循环负数倒数 - int 类型不支持运算符..-

标签 f#

我尝试在非递归阶乘函数中从 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/

相关文章:

f# - 将 OCaml 转换为 F# : Converting OCaml open_box and close_box to F#

f# - 如何在 F# 中使用 Observable.Zip

F# 注释错误

F#:如何求笛卡尔幂

arrays - 在 F# 中访问 GetSlice 方法

f# - Intellisense 错误和 #I 与脚本文件

f# - F# 中的 mixin 或 trait

c# - 默认情况下,F# 中的引用是否不可为空?

f# - 无法从 C# 类使用 F# 中的某些方法

oop - 有人可以指出 F# 中的多范式(对象功能)编程示例吗?