2
这里我试图使用命令式样因式函数,但尽管函数的最后一行声明返回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
谢谢你在我的函数指出错误。但是,删除第一个函数只会消除第二个错误,并且在for循环之后删除一个错误会给出一个错误消息,说明我有一个不完整的结构化构造函数。您提供的替代函数也会给我提供第一个错误。 – GuitarGuy365
@ GuitarGuy365你需要在'for for'之后的'do'。我会看看你的其他错误,但我测试了这个代码,它的工作。 – TheInnerLight
@GuitarGuy365我认为你的程序结尾没有'0'。在'printfn ...'之后的新行添加'0'。 'main'应该返回'int'。 – TheInnerLight