Pattern Matching in F#

Introduction

Pattern matching allows us to make different computation depending on matching pattern. It is very similar to Switch statement in c and c++. Its syntax is given below.

match exp with
| pattern1 -> result
| pattern2 -> result
|------------------
|------------------
| _ -> default


Now we write the code for getting day name by passing day number. Like following code.

let week n =
  match n
with
 
  | 1 ->
"Monday"
  | 2 ->
"Tuesday"
  | 3 ->
"Wednesday"
  | 4 ->
"Thursday"
  | 5 ->
"Friday"
  | 6 ->
"Saturday"
  | 7 ->
"Sunday"
  | _->
"Wrong Input"

printfn "%s" (week 1)
printfn "%s" (week 2)
printfn "%s" (week 5)

printfn "%s" (week 9)

Output:

pattern matching in F#

Ebook Download
View all
Learn
View all