F # Tutorial-if statement

Source: Internet
Author: User

Last time we used for a for loop processing. This time we learn if statements. A simple example is as follows:

#light
let add x y = x + y
if add 2 3 = 5 then printfn "2 + 3 = 5"
if add 2 3 = 6 then printfn "2 + 3 = 6" else printfn "2 + 3 != 6"

When compared with a single =, rather than the usual habit of = =. In addition, it should all be very common. The next example is:

let even = if 10 % 2 = 0 then true else false
printfn "%A" even

What you need to notice here is that the IF statement has a value. The action feels similar to the three-mesh operator in C #.

In this case, the value of the IF statement is used as the initial value of the even variable. An if statement with a value cannot be written like this:

Let ten = if add a B < ten then 10

The reason is that the Else branch has no value, is the unit type, so it is inconsistent with the type of the then branch, so there will be a compilation error.

Of course, you can also use else if.

let lang = "VB"
if lang = "C#" then
     printfn "This is C#"
else if lang = "F#" then
     printfn "This is F#"
else
     printfn "Other"

By the way, the ELIF keyword can be used instead of else if.

if lang = "C#" then
     printfn "This is C#"
elif lang = "F#" then
     printfn "This is F#"
else
     printfn "Other"

You can also use && and | | :

let aa = 1
let bb = 2
if aa = 1 && bb = 2 then printfn "Both are true"
if aa = 2 || bb = 2 then printfn "Either is true"

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.