函数返回类型单位而不是类型ref

时间:2015-12-31 15:05:46

标签: f# return-type ref imperative

这里我试图使用命令式样式因子函数,但是尽管函数的最后一行声明要返回ref,fsc告诉我该函数正在返回一个单元。我知道不允许返回mutables,但我认为你可以通过使用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

1 个答案:

答案 0 :(得分:2)

您需要做的只是删除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