64 people like it.

Active pattern for let binding inside patterns

The Let active pattern demonstrated by this snippet can be used to assign values to symbols in pattern matching. This is useful for writing complex pattern matching using match as we can handle multiple cases using a single clause.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
// Active pattern that can be used to assign 
// values to symbols in a pattern
let (|Let|) value input = (value, input)

// This is useful when writing complex pattern matching
let flag, num = (...)
match flag, num with
| true, (Let "one" (str, 1) | Let "two" (str, 2) | Let "three" (str, 3)) ->
    // Called when number is between 1 and 3 and assigns textual 
    // representation of the number to 'str' (so that we can handle all
    // cases with just a single match clause)
    printfn "%s" str
| _ -> 
    printfn "Something else"
val value : 'a
val input : 'b
val flag : bool

Full name: Script.flag
val num : int

Full name: Script.num
true, 0
active recognizer Let: 'a -> 'b -> 'a * 'b

Full name: Script.( |Let| )
val str : string
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn

More information

Link:http://fssnip.net/21
Posted:13 years ago
Author:Tomas Petricek
Tags: active pattern , pattern matching