Type Tests with Pattern Matching in F# October, 2009
I'm working on an application where I'm sending output to a console window. If the output is an integer or double I wanted the print function to perform special formatting. For everything else just call .ToString(). Page 115 in Expert F# shows an example of how to do this sort of thing with pattern matching, here is an example (Stripped down for clarity):
let Print (t:obj) = let text = match t with | :? int -> (t :?> int).ToString("#,###") | :? double -> (t :?> double).ToString("#,###.0") | _ -> t.ToString() ... Console.Write(text)
Update: Like Don mentioned in the comments there is a much more succinct way to write this using ":? int as i". Thanks Don!
let Print (t:obj) = let text = match t with | :? int as t -> t.ToString("#,###") | :? double as t -> t.ToString("#,###.0") | _ -> t.ToString() ... Console.Write(text)
A few points:
- The compiler complained that I didn't have a type annotation on the parameter. Not sure why this is but book shows that annotating it as an obj does the trick.
- The :?
construct looks at the type of the value.
- The :?> operator casts the value down to a particular type.