Thursday, January 24, 2013

Tips for F# pattern match (2)

(In learning from "Programming F# 3.0, 2nd Edition")
(continued from phosphorescence: Tips for F# pattern match (1))

If you want to declare some constants out of any pattern matches, simple let binding is not allowed. Because simple binding is not recognized, it is recognized as "value capture".
let person_01_name = "Robert";;
let person_01_nickname = "Bob";;
let person_02_name = "William";;
let person_02_nickname = "Bill";;
let greet name =
  match name with
    | person_01_name -> printfn "Hello, %s" person_01_nickname
    | person_02_name -> printfn "Hello, %s" person_02_nickname
    | x -> printfn "Hello, %s" x;;
      | person_02_name -> printfn "Hello, %s" person_02_nickname
  ------^^^^^^^^^^^^^^

stdin(8,7): warning FS0026: This rule will never be matched

      | x -> printfn "Hello, %s" x;;
  ------^

stdin(9,7): warning FS0026: This rule will never be matched

How do we do for? The answer is: using "literal binding".
  1. Add [<Literal>] atrribute
  2. Change an initial character of variable to upcase
[<Literal>]
let Person_01_name = "Robert";;
let person_01_nickname = "Bob";;
[<Literal>]
let Person_02_name = "William";;
let person_02_nickname = "Bill";;
let greet name =
  match name with
    | Person_01_name -> printfn "Hello, %s" person_01_nickname
    | Person_02_name -> printfn "Hello, %s" person_02_nickname
    | x -> printfn "Hello, %s" x;;

(continue to phosphorescence: Tips for F# pattern match (3))

No comments:

Post a Comment