F# Review

Today I encountered pattern matching for the first time.

C# has it too, but I felt this is a feature characteristic of F#.

F# Pattern Matching

This is amazing. I thought C#’s switch expression pattern matching was similar, but this feature probably went from F# to C#.

match Expression

I think the match expression will be used often, so I need to remember it well.

Also, it seems there are different kinds of patterns like or patterns and as patterns, so I need to memorize these properly too.

let testFunc param =
    match param with
        | 'a' -> 0
        | 'b' -> 1
        | _ -> -1
       
let ret = testFunc 'b'
printfn "%A" ret

function Expression

Simply put, it seems to be a combination of the fun expression and the match expression.

I thought it could be created with if statements even without function, but how is it really??

let testFunc = function 
    | value when value > 0 -> 1
    | value when value < 0 -> -1
    | _ -> 0

let ret = testFunc 2
printfn "%A" ret

Records

Is this equivalent to class in C#?

It doesn’t seem to have functions though.

But to avoid side effects, is it better to create it by passing a record type as an argument?

Like C# extension methods.

// Define the record type first
type Favorite = { color: string; number: int; music: string }

let favorite = { color = "red"; number = 7; music = "Jazz" } 
let { color = favoriteColor; number = favoriteNumber; music = favoriteMusic} = favorite 
printfn "%s, %d, %s" favoriteColor favoriteNumber favoriteMusic

Discriminated Unions

My understanding of this is really low right now.

It’s said to be close to enum, but since it can have associated values, it seems difficult to master.

But it feels like it would be satisfying if used well.

type Fruits = 
    | Apple
    | Orange
    | Grape

let favoriteFruits = Apple

printfn "%A" favoriteFruits

I’m taking it slow, so that’s all for today. I haven’t even read half of the book yet, when will I finish—.