Skip to content

Instantly share code, notes, and snippets.

@misterspeedy
Created September 12, 2017 19:59
Show Gist options
  • Save misterspeedy/675f0565417ce5133f8ba3588884e2b4 to your computer and use it in GitHub Desktop.
Save misterspeedy/675f0565417ce5133f8ba3588884e2b4 to your computer and use it in GitHub Desktop.
Source code for "Casual F# - Pattern Matching"
namespace CasualFSharp
module PatternMatching =
let describeInt i =
match i with
| 1 -> "One"
| 2 -> "Two"
| _ -> "Many"
let tryFirst (items : string list) =
match items with
| [] -> None
| f :: _ -> Some f
let firstOrDefault dflt (items : string list) =
match tryFirst items with
| Some x -> x
| None -> dflt
let printFirstFew (items : string list) =
match items with
| [] -> printfn "Empty list"
| [a] -> printfn "One element: %s" a
| [a; b] -> printfn "Two elements: %s %s" a b
| a :: b :: _ -> printfn "More than two: %s %s ..." a b
type MayHap<'T> =
| Summat of 'T
| Nowt
let tryFirst2 (items : string list) =
match items with
| [] -> Nowt
| f :: _ -> Summat f
let firstOrDefault2 dflt (items : string list) =
match tryFirst2 items with
| Summat x -> x
| Nowt -> dflt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment