Saturday, March 16, 2013

Active Pattern (3) : Parameterized Active Pattern

(In learning from "Programming F# 3.0, 2nd Edition")

Parameterized Active Pattern takes both condition to match and parameter of its condition, and also used with Partial Active Pattern as "Parameterized Partial Active Pattern".

let (|MultiplesOf|_|) (multiplier : int) (input : int) =
    if (input % multiplier = 0) then Some(input) else None

let fizzBuzz input =
    match input with
    | MultiplesOf 5 _ & MultiplesOf 3 _ -> "FizzBuzz"
    | MultiplesOf 5 _ -> "Buzz"
    | MultiplesOf 3 _ -> "Fizz"
    | _ -> input.ToString()

List.map fizzBuzz [1..40];;

No comments:

Post a Comment