V F# môžme pattern match využiť pri spracovaní výnimiek, je to celkom fajn syntax.
open System
printf "Enter a number: "
let value = Console.ReadLine()
let n =
match Int32.TryParse value with
| true, num -> num
| _ -> failwithf "'%s' is not an integer" value
let f = function
| value when value > 0 -> printfn "positive value"
| value when value = 0 -> printfn "zero"
| value when value < 0 -> printfn "negative value"
f (int value)
f n
Operátor :? je pre dátové typy. F# nemá union types ako napr. Scala, tak som vytiahol ArrayList. (bŕŕ, Java hovadina sa dostala do F# !)
open System.Collections
type User =
{ FirstName: string
LastName: string
Occupation: string }
let vals = new ArrayList()
vals.Add(1.2)
vals.Add(22)
vals.Add(true)
vals.Add("falcon")
vals.Add(
{ FirstName = "John"
LastName = "Doe"
Occupation = "gardener" }
)
for wal in vals do
match wal with
| :? int -> printfn "an integer"
| :? float -> printfn "a float"
| :? bool -> printfn "a boolean"
| :? User -> printfn "a User"
| _ -> ()
Alebo sa tiež používajú tzv. active patterns, kde si zadefinujeme názvy, ktoré potom neskôr použijeme.
let (|RegEx|_|) p i =
let m = Regex.Match(i, p)
if m.Success then
Some m.Groups
else
None
let CheckRegex (msg) =
match msg with
| RegEx @"\d+" g -> printfn "Digit: %A" g
| RegEx @"\w+" g -> printfn "Word : %A" g
| _ -> printfn "Not recognized"
CheckRegex "an old falcon"
CheckRegex "1984"
CheckRegex "3 hawks"
Niektoré jazyky používajú switch expressions alebo (given)/when syntax pre to isté. Veľmi dobre to má Groovy, ktorý zvláda regulárne výrazy, listy, mapy alebo range.
def testSwitch(val) {
switch (val) {
case 52 -> 'Number value match'
case "Groovy 4" -> 'String value match'
case ~/^Switch.*Groovy$/ -> 'Pattern match'
case BigInteger -> 'Class isInstance'
case 60..90 -> 'Range contains'
case [21, 'test', 9.12] -> 'List contains'
case 42.056 -> 'Object equals'
case { it instanceof Integer && it < 50 } -> 'Closure boolean'
case [groovy: 'Rocks!', version: '1.7.6'] -> "Map contains key '$val'"
default -> 'Default'
}
}