3 people like it.

function keyword for pattern matching

Strangely enough, really useful documentation of F#'s "function" keyword used for pattern matching is difficult to find within Microsoft's official documentation. A Google search turns up some helpful illustrations and discussions of the keyword. Here's a simple example that some might find useful.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
type Oddness =
| IsOdd
| IsEven

let getOddness = 
   function 
   | n when (n % 2)= 0 -> IsEven
   | _ -> IsOdd

getOddness 7 |> printfn "%A"
getOddness 12 |> printfn "%A"
union case Oddness.IsOdd: Oddness
union case Oddness.IsEven: Oddness
val getOddness : _arg1:int -> Oddness

Full name: Script.getOddness
val n : int
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
Raw view New version

More information

Link:http://fssnip.net/kf
Posted:4 years ago
Author:musicologyman
Tags: pattern matching