Friday, November 9, 2012

F# ≥ C# (Pattern matching)

let us look at the following code first:

let a = 1       //nothing fancy
let b = 1, 2  // b is tuple now

The b is a tuple.  For a C# developer who wants to get the first and second element of the tuple, the obvious way is to call fst and snd function. Now we can use pattern matching

let c,d = b   // c = 1 and d = 2

now let us decompose a list
let l = [1;2;3;4]
match l with
| h::t -> ...     // h is 1 and t is [2;3;4]
| _ -> ...
match l with
| h0::h1::t -> ... // h0 is 1, h2 is 2, and t is [3;4]
| _ -> ...
Or you can decompose the list if the list length is known.
match l with
| [a;b;c;d] ->     //a=1, b=2, c=3, and d=4
| _ -> ...
I do not know how to use C# code to do the same thing. :)


No comments: