您可以定义一种简单的域特定语言(DSL)来表达这些类型的规则.与"解析器"对应的类型实际上只是一个采用日期并返回布尔值的函数:
type DateClassifier = DC of (DateTime -> bool)
Run Code Online (Sandbox Code Playgroud)
您可以轻松定义一些简单的函数:
// Succeeds when the date is wednesday
let wednesday = DC (fun dt -> dt.DayOfWeek = DayOfWeek.Wednesday)
// Succeeds if the date is after specified limit
let after limit = DC (fun dt -> dt > limit)
// Succeeds if the day is the specified value
let day d = DC (fun dt -> dt.Day = d)
// Takes two date classifiers and succeeds if either of them succeeds
let (<|>) (DC f) (DC g) = (fun dt -> f dt || g dt)
// Takes two date classifiers and succeeds if both of them succeed
let (<&>) (DC f) (DC g) = (fun dt -> f dt && g dt)
Run Code Online (Sandbox Code Playgroud)
要指定你的条件 - "在本月5日之后的下一个星期三" - 你需要一个助手,它可以在第5天之后的任何一天产生成功的功能,这可以这样做(这有点效率低,但它是使用现有基元的组合,这很好):
let afterDay d =
[ for n in d + 1 .. 31 -> day n ] |> Seq.reduce (<|>)
Run Code Online (Sandbox Code Playgroud)
您的规范(或"解析器")只会在您描述的那一天成功:
after DateTime.Now (wednesday <&> afterDay 5)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
270 次 |
| 最近记录: |