Search code examples
functionrecursionf#let

Can not define a recursive method with let key word in F#


I am learning F# with VS.

Would you tell me why compiler gives me an error FS3118 with the code below?

The "let" before sumToN is marked with red under line...

FS3118: Incomplete value or function definition. If this is in an expression, the body of the expression must be indented to the same column as the 'let' keyword.

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

How should I correct the code?


Solution

  • It's the zero on the very last line. Because it is indented one character to the right, it is considered part of the let sumToN block.

    And therefore, the whole function main looks like it only has one let in its body and no lines after the let.

    This is incorrect syntax in F#. If there are no lines to execute in the body of the function, such function does nothing, and therefore it doesn't make sense to have it.

    To fix, unindent the zero:

    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