5 people like it.

Use of Partial-Case with Parameters

Depicts use of one kind of active pattern matching; partial-case with parameters.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
    //A record type to hold name and age
    type Person = {Name: string; Age: int}

    //Partial active pattern with two argus
    let (|Young|_|) age (lst: list<Person>) =
        lst |> List.mapi(fun i _ -> (lst.Item i).Age) |> List.tryFind(fun i -> i <= age)

    //A matching funtion
    let findAYoungAge = function
        | Young 25 yr -> printfn "Found a young age of %d" yr
        | _ -> printfn "Couldn't find any ages younger than 25"

    //Construct a list of record values
    let listOfPerson = [{Name="John"; Age=29}; {Name="Simon"; Age=24}; {Name="Shirley"; Age=50}]

    //"Found a young age of 24"
    findAYoungAge listOfPerson
Person.Name: string
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
Person.Age: int
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
val age : int
val lst : Person list
type 'T list = List<'T>

Full name: Microsoft.FSharp.Collections.list<_>
type Person =
  {Name: string;
   Age: int;}

Full name: Script.Person
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
  interface IEnumerable
  interface IEnumerable<'T>
  member Head : 'T
  member IsEmpty : bool
  member Item : index:int -> 'T with get
  member Length : int
  member Tail : 'T list
  static member Cons : head:'T * tail:'T list -> 'T list
  static member Empty : 'T list

Full name: Microsoft.FSharp.Collections.List<_>
val mapi : mapping:(int -> 'T -> 'U) -> list:'T list -> 'U list

Full name: Microsoft.FSharp.Collections.List.mapi
val i : int
property List.Item: int -> Person
val tryFind : predicate:('T -> bool) -> list:'T list -> 'T option

Full name: Microsoft.FSharp.Collections.List.tryFind
val findAYoungAge : _arg1:Person list -> unit

Full name: Script.findAYoungAge
active recognizer Young: int -> Person list -> int option

Full name: Script.( |Young|_| )
val yr : int
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val listOfPerson : Person list

Full name: Script.listOfPerson
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/46
Posted:13 years ago
Author:Joel Huang
Tags: active pattern