Conditions and iterations in F#

Conditions
This code will first assign a value to a and b, and print the values out. Thereafter, it will assign a value to c, that depends on the value of a. The value will be 20. Finally, it will print out both a, b and c.
A programmer at NASA.

let a=1
let b=2
printfn "%d %d" a b

let c=
if a=0 then 10
elif a=1 then 20
else 30

printfn "%d %d %d" a b c

Iterations
This code will print eleven numbers on screen, from 10 to 20:

for x in 10..20 do printfn "%d" x

Unlike Visual Basic and C#, indentations actually means something in F#. Look at this iteration. The output is one two one two one two:

for x in 1..3 do
printfn "one"
printfn "two"

But just by changing the indentation (removing the indentation before the second prinfn), the output is changed to one one one two. The second printfn is no longer a part of the iteration.

for x in 1..3 do
printfn "one"
printfn "two"

You can also do while-iterations, that is, iterations that executes while a condition is true.

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll:

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Comments

Important information: If you have not commented before, your comment will be reviewed before it is published. This means that you will not see it immediately, but I have received it. This is not because I want to filter comments, but because I want to prevent spam and advertising.

Leave a Reply

Your email address will not be published. Required fields are marked *