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