在这里,我尝试使用命令式阶乘函数,但尽管函数的最后一行声明ref
要返回 a,但 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