F# for C# Developers by Tao Liu

F# for C# Developers by Tao Liu

Author:Tao Liu
Language: eng
Format: epub, pdf
Tags: COMPUTERS / Programming / Microsoft Programming
ISBN: 9780735670211
Publisher: Microsoft Press
Published: 2013-06-11T04:00:00+00:00


Note

The underscore (_) in the second pattern match instructs the F# compiler to ignore the returned value from the active pattern.

Note

Active patterns cannot return more than seven possibilities. So the code let (|A|B|C|D|E|F|G|H|I|J|K|) x = x will generate a compile error.

Using Parameterized Active Patterns

The active pattern is a special function. If it is a function, can it accept parameters? The answer is yes. Parameters for an active pattern can be included immediately after the active pattern label, but they must appear before the active pattern return value. Example 6-60 shows how to parse a phone number and return all numbers in that phone number. The pattern string is the parameter and the out variable is used to store the return value from the active pattern.

Example 6-60. Parameterized active pattern example

open System.Text.RegularExpressions // define the parameterized active pattern let (|RegexMatch|_|) (pattern:string) (input:string) = let regex = Regex(pattern).Match(input) if regex.Success then Some(List.tail [ for x in regex.Groups -> x.Value]) else None let parsePhoneNumber str = match str with | RegexMatch "(\d{3})-(\d{3})-(\d{4})" out -> System.String.Join("", out) | RegexMatch "(\d{3})-(\d{3})(\d{4})" out -> System.String.Join("", out) | _ -> "Not supported format" // two statements below show 4251231234 parsePhoneNumber "425-123-1234" parsePhoneNumber "425-1231234" // this format does not parse and shows "Not supported format" parsePhoneNumber "(425)123-1234"



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.