F# For Dummys - Day 9

78 阅读1分钟

Today we learn control flow, or branching
sometimes we need to execute a block of code only when it meets some condition

//Pseudocode
if conditionOne then doTaskOne
else if conditionTwo then doTaskTwo
else doSomethingElse

we introduce 2 ways of branching

if...then

let x = 10

if x > 0 then
    printfn "Positive"
elif x = 0 then
    printfn "Zero"
else
    printfn "Negative"

x = 10, only the branch if x > 0 suits, the rest logic will not execute

match

// Match expression. 
match test-expression with
| pattern1 [ when condition ] -> result-expression1
| pattern2 [ when condition ] -> result-expression2
| ...

equivalent example:

let x = 10

match x with
| x when x > 0 -> printfn "Positive"
| x when x = 0 -> printfn "Zero"
| _ -> printfn "Negative"

AND Pattern: we can combine conditions with (&&) operator, it hits when both condition match

let age = 10

match age with
| age when age > 0 && age < 14 -> printfn "Teenager"
| age when age > 14 -> printfn "Adults"
| _ -> printfn "Not born"

OR Pattern: we can combine patterns using the (||) operator to match multiple patterns

let x = 10

match x with
| x when x > 0 || x = 0 -> printfn "Positive or Zero"
| _ -> printfn "Negative"

we can even define a pattern matching function

type Shape =
    | Square of side: double
    | Rectangle of width: double * length: double

let getArea shape =
    match shape with
    | Square side -> side * side
    | Rectangle (width, length) -> width * length

let square = Square 2.0
printfn $"The area of the square is {getArea square}"
let rect = Rectangle (2.0, 3.0)
printfn $"The area of the rect is {getArea rect}"

getArea function calculate the area according to different shape

The area of the square is 4
The area of the rect is 6

we didn't learn type yet, it defines a Union type here, and there is more powerful usage of match, we will introduce type, Union and discover more usage of match in the coming days