Active pattern with arguments

Category:
Active patterns
Description: Active pattern determines the input value format by using an active pattern with arguments.
Code:
let ActivePatternSample2() = 
let ( |Bool|Int|Float|String| ) input =
let sucess, res = Boolean.TryParse input
if sucess then Bool(res)
else
let sucess, res = Int32.TryParse input
if sucess then Int(res)
else
let sucess, res = Double.TryParse input
if sucess then Float(res)
else String(input)
let printInputWithType input =
match input with
| Bool b -> printfn "Boolean: %b" b
| Int i -> printfn "Integer: %i" i
| Float f -> printfn "Floating point: %f" f
| String s -> printfn "String: %s" s
printInputWithType "true"
printInputWithType "12"
printInputWithType "-12.1"

Execution Result:
Boolean: true
Integer: 12
Floating point: -12.100000

Last edited Sep 14, 2011 at 3:17 AM by ttliu2000, version 1

Comments

No comments yet.