Pages

Thursday, October 4, 2012

Record and pattern matching

The record and pattern matching is a little tricky. Let us assume we have record type like the following.

    type MyRecord = { X : int list; Y : string }
    type MyRecord2 = { XX : int; YY : string; Z : int }


    let rr = { X = [100;200;300]; Y="aa" }
    let r0 = { X = [100;200;3]; Y="aa" }
    let r1 = { XX = 1; YY = "bb"; Z=9 }

    match r1 with
    | rr -> "a"
    | _ -> "b"

Execution result is "a". The record will match any record even the record is different types. 

The right way to crack the record open is to use:

    match r1 with
    | {YY=yValue} -> yValue
    | _ -> "b"

The yValue will be set to "bb".

No comments: