2015-12-31 61 views
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 

回答

2

所有你需要做的是去除dodo在这种情况下使用的是专门为表演方 - 效应,因此是单位的预期回报类型。

此外,您的功能不正确,您需要在循环中将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 
+0

谢谢你在我的函数指出错误。但是,删除第一个函数只会消除第二个错误,并且在for循环之后删除一个错误会给出一个错误消息,说明我有一个不完整的结构化构造函数。您提供的替代函数也会给我提供第一个错误。 – GuitarGuy365

+0

@ GuitarGuy365你需要在'for for'之后的'do'。我会看看你的其他错误,但我测试了这个代码,它的工作。 – TheInnerLight

+0

@GuitarGuy365我认为你的程序结尾没有'0'。在'printfn ...'之后的新行添加'0'。 'main'应该返回'int'。 – TheInnerLight