F # Tutorials: recursion

Source: Internet
Author: User

So far we've learned about if, for, and while, so we can try to write some simple programs.

Let's try to write a program that calculates the sum from 1 to the specified number. First defines a sumtotal function that reads the specified value from the keyboard as an input parameter.

#light
let SumTotal n =
         let mutable ttl = 0
         for i = 1 to n do
              ttl <- ttl + i
         ttl
let s = stdin.ReadLine()
let num = System.Int32.Parse(s)
printfn "%d" (SumTotal num)

Using mutable, you can make the TTL a variable variable.

There is a line of code that has only TTL, and the same function as C # 's return TTL.

The input of the keyboard can be done by stdin. ReadLine implementation.

Since it is not known how to transform from string to numerical, use the int32.parse of the. NET Framework first.

While this is the requirement, you should avoid using the re-assignment of variables as much as possible in F #. Let's try rewriting the code. This seems to work only with recursion. You should use the REC keyword when defining recursive functions.

let rec SumTotal n =
         if n = 1 then 1
         else n + SumTotal (n-1)
let s = stdin.ReadLine();
let num = System.Int32.Parse(s)
printfn "%d" (SumTotal num)

Look at this kind of code, is not the mathematical definition of summation is very similar ah?

x = 1 : f(x) = 1
x > 1 : f(x) = x + f(x-1)

With such a definition it is easy to get the SumTotal function mentioned above.

If the code in the Else section is rewritten as:

else n + sumtotal n-1

This can cause infinite loops and cause stackoverflow. The same is true for PRINTFN parameters in the last line. It seems that the operators of F # are prioritized in sequence, or somewhat biased with the feeling.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.