【问题标题】:Function returning type unit instead of type ref函数返回类型单元而不是类型 ref
【发布时间】:2016-04-05 12:41:30
【问题描述】:

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

【问题讨论】:

    标签: f# return-type ref imperative


    【解决方案1】:

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

    【讨论】:

    • 感谢您指出我的函数中的错误。但是,删除第一个 do 只会消除第二个错误,并且在 for 循环之后删除一个会给出一个错误,即我的结构化构造不完整。您提供的替代函数也给了我第一个错误。
    • @GuitarGuy365 你需要dofor 之后。我将查看您的其他错误,但我测试了此代码并且它有效。
    • @GuitarGuy365 我认为您的程序末尾没有0。在printfn... 之后的新行中添加0main 应该返回 int
    • 就是这样!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多