4 people like it.

Different styles of pattern matching

For tutorial, the same functionality, different styles of pattern matching.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
41: 
let MyFunction1 a =
   if a = "A" then 1
   elif a = "B" then 2
   else 3

let MyFunction2 a = 
   match a with
   | "A" -> 1
   | "B" -> 2
   | _ -> 3

let MyFunction3 = fun a -> 
   match a with
   | "A" -> 1
   | "B" -> 2
   | _ -> 3

let MyFunction4 = function
   | "A" -> 1
   | "B" -> 2
   | _ -> 3

let MyFunction5 a = 
   match a with
   | x when x = "A" -> 1
   | x when x = "B" -> 2
   | x -> 3


let MyFunction6 a = 

    let (|FirstVowel|FirstConsonant|Other|) p =
        match p with
        | "A" -> FirstVowel
        | "B" -> FirstConsonant
        | _ -> Other

    match a with
    | FirstVowel -> 1
    | FirstConsonant -> 2
    | Other -> 3
val MyFunction1 : a:string -> int

Full name: Script.MyFunction1
val a : string
val MyFunction2 : a:string -> int

Full name: Script.MyFunction2
val MyFunction3 : a:string -> int

Full name: Script.MyFunction3
val MyFunction4 : _arg1:string -> int

Full name: Script.MyFunction4
val MyFunction5 : a:string -> int

Full name: Script.MyFunction5
val x : string
val MyFunction6 : a:string -> int

Full name: Script.MyFunction6
val p : string
active recognizer FirstVowel: string -> Choice<unit,unit,unit>
active recognizer FirstConsonant: string -> Choice<unit,unit,unit>
active recognizer Other: string -> Choice<unit,unit,unit>
Raw view Test code New version

More information

Link:http://fssnip.net/mj
Posted:10 years ago
Author:Tuomas Hietanen
Tags: pattern matching