f# - 函数返回类型unit而不是类型ref

标签 f# return-type ref imperative

在这里,我尝试使用命令式阶乘函数,但尽管函数的最后一行声明要返回 ref,但 fsc 告诉我该函数正在返回一个单位。我知道不允许返回可变值,但我认为您可以通过使用 ref 来规避这一点?另外,请不要告诉我以函数式方式重写它。我知道这是一种替代方案,但我试图更好地理解命令式编程在该语言中的工作原理。

这是我的程序:

let factorial n = do
    let res = ref 1
    for i = 2 to n do
        res := !res * i
    res 

[<EntryPoint>]
let main(args : string[]) = 
    let result = factorial 10
    printfn "%d" !result

这是编译器给我的:

factorial.fs(2,5): warning FS0020: This expression should have type 'unit',     but
has type 'int ref'. Use 'ignore' to discard the result of the expression, 
or 'let' to bind the result to a name.

factorial.fs(10,13): error FS0001: Type mismatch. Expecting a
    'a -> int
but given a
    'a -> unit
The type 'int' does not match the type 'unit'

factorial.fs(10,19): error FS0001: This expression was expected to have type
    'a ref
but here has type
    unit

最佳答案

您需要做的就是删除 do,在此上下文中使用的 do 专门用于执行副作用,因此是单位的预期返回类型。

另外,你的函数不正确,需要在循环中将n替换为i

let factorial n =
    let res = ref 1
    for i = 2 to n do
        res := !res * i
    res

顺便说一句,你不需要使用引用,你可以这样写:

let factorial n =
    let mutable res = 1
    for i = 2 to n do
        res <- res * i
    res 

关于f# - 函数返回类型unit而不是类型ref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34548173/

相关文章:

F#和xna字体问题

c# - 从传递给 C# 的 F# 列表中检索项目

c++ - 没有返回类型的函数

c# - 为什么 C# 或 C++ 不能根据返回类型区分方法?

c# - 通过引用从 c# COM Visible 类中的 c# 方法返回 vb 变体

f# - 为什么 F# 的类型推断不能处理这个问题?

f# - 纸牌游戏的遗传算法(Dominion)

c - Main() 中是否需要返回一个值?

c# - 我是否使用 ref 正确传递我的参数?

.net - 从托管 'ref' 内部指针恢复包含 GC 对象