Thursday, March 14, 2013

Active Pattern (2) : Partial Active Pattern

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

If your "Single-case Active Pattern" should be considered for dealing option type (e.g. phosphorescence: Active Pattern (1) : Single-case Active Pattern: this sample is NOT considering invalid date), you should define as "Partial Active Pattern" like below:
> open System;;
> let (|WhatDayOfWeek|_|) (year, month, day) =
-     try
-         Some(System.DateTime(year,month,day).DayOfWeek)
-     with
-     | :? System.ArgumentOutOfRangeException -> None;;

val ( |WhatDayOfWeek|_| ) : year:int * month:int * day:int -> DayOfWeek option

> let weekEnd year month day =
-     match (year, month, day) with
-     | WhatDayOfWeek System.DayOfWeek.Sunday
-     | WhatDayOfWeek System.DayOfWeek.Saturday
-         -> "Week End !!"
-     | WhatDayOfWeek _
-         -> "Not Week End..."
-     | _ -> "invalid date";;

val weekEnd : year:int -> month:int -> day:int -> string

> weekEnd 2013 3 15;;
val it : string = "Not Week End..."
> weekEnd 2013 3 16;;
val it : string = "Week End !!"
> weekEnd 2013 2 29;;
val it : string = "invalid date"

No comments:

Post a Comment