【问题标题】:Can not define a recursive method with let key word in F#无法在 F# 中使用 let 关键字定义递归方法
【发布时间】:2020-07-23 19:20:09
【问题描述】:

我正在用 VS 学习 F#。

你能告诉我为什么编译器在下面的代码中给我一个错误 FS3118 吗?

sumToN 前面的“let”在行下用红色标记...

FS3118:值或函数定义不完整。如果 this 在表达式中,则表达式的主体必须缩进到与 'let' 关键字相同的列。

open System
[<EntryPoint>]
let main argv =
   let sumToN n = let rec f s n = if n > 0L then f (s+n) (n-1L) else s in f 0L n
   //let sum = sumToN(5L)
   //do printfn "%i" sum |> ignore
    0

我应该如何更正代码?

【问题讨论】:

    标签: function recursion f# let


    【解决方案1】:

    最后一行是零。因为它向右缩进一个字符,所以它被认为是let sumToN 块的一部分。

    因此,整个函数main 看起来它的主体中只有一个letlet 之后没有行。

    这是 F# 中的错误语法。如果函数体中没有要执行的行,则该函数什么也不做,因此拥有它没有意义。

    要修复,取消缩进零:

    let main argv =
       let sumToN n = let rec f s n = if n > 0L then f (s+n) (n-1L) else s in f 0L n
       //let sum = sumToN(5L)
       //do printfn "%i" sum |> ignore
       0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 2016-08-05
      • 2017-02-16
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      • 2018-11-01
      相关资源
      最近更新 更多