2
votes

I have a function

let simpleSum n =
    let s = n * (n+1)/2
    printf "%A " s
let result = simpleSum 10

I now want to make it recursive; tail-recursion without added variables is preferred. There is something wrong with my statement: if n <= 0 then 0

 let rec recSum n = 
     if n <= 0 then
         0
     else
         recSum n*(n+1)/2
 recSum 4

I run into the error:

FS0020: The result of this expression is implicitly ignored. 
Consider using 'ignore' to discard this value explicitly, e.g. 'expr :> ignore',
or 'let' to bind the result to a name, e.g. 'let result = expr'.

How do I fix this? I want to avoid variables.

1
What's not working? what errors/issues are you running into? - mosca125
What's the point of that while loop? In which cases would the result be any different than just let sum n = n * (n+1) / 2? - sepp2k
The while loop is not necessary I know, but was a requirement in my assignment. I run into the error: FS0020: The result of this expression is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr :> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'. I want to avoid variables here. - DonutSteve
Are you sure you didn't misunderstand your assignment? You can either calculate the sum using a loop/recursion or you can use the formula. Doing both at the same time makes no sense. - sepp2k
First assignment was to use a loop. Second assignment was to use recursion. Right now I am just trying to make the recursion work. The sum should add up to the same. - DonutSteve

1 Answers

2
votes

I am not going to do your assignment for you. However, I will show you the usual way to transform a loop into a recursive function.

This is the "imperative" way to do a factorial.

let factorial n = 
    let mutable acc = 1
    let mutable iter = 1 
    while iter <= n do 
        acc <- acc * iter
        iter <- iter + 1 
    acc 

And here it is in a recursive implementation :

let recFactorial n = 
    let rec loop acc iter = 
        if iter > n then acc else 
        loop (acc*iter) (iter+1) 
    loop 1 1 

You will see I defined the actual recursive function inside my bigger function. I believe it makes the code cleaner this way.

There are many ways, subtly different, to change a while or for loop into a recursive function, but this I think shows you how the one-to-one relationship works.

Your code gets stuck in an infinite loop when I call sum 1 btw. Crashed my editor.

Edit: Incidentally, the "naïve" way to do a Factorial recursive function is this

let rec recFactorial n = 
    if n = 1 then 1 else 
    n * recFactoiral (n-1)

However, this is not recommended and will crash your program quickly due to stack overflow. Any article on Tail Recursion (what I did the first time) will explain why this is in a much better way than I can.