문제

Are there some 'date parser' library that does for dates what FParsec does to strings ?

That is, you either specify rules and it will match against them to recognize the supplied patterns.


Conversely, are there any libraries to generate dates based on some parsing rules ? The idea would be to supply user with a 'real time' completion to guide him to a valid future fparsec matching.

(does this problem of generative parsing has a name in the secluded parsing circles ?)

도움이 되었습니까?

해결책

You can define a simple domain specific language (DSL) to express these kinds of rules. The type corresponding to your "parser" is actually just a function that takes a date and returns boolean:

type DateClassifier = DC of (DateTime -> bool)

You can easily define some simple functions:

// 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)

To specify your condition - "the next wednesday after the 5th of the month" - you'll need a helper that generates function that succeeds on any day following 5th, which can be done like this (this is a bit inefficient, but it is composition using existing primitives, which is nice):

let afterDay d = 
  [ for n in d + 1 .. 31 -> day n ] |> Seq.reduce (<|>)

Your specification (or "parser") that only succeeds for the day you described is then:

after DateTime.Now (wednesday <&> afterDay 5)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top