2012-04-30 60 views
0

是否有一些'日期解析器'庫爲FParsec做字符串的日期嗎?解析日期與F#

也就是說,您要麼指定規則,而是要匹配它們來識別提供的模式。


相反,還有什麼庫基於一些分析規則的日期? 這個想法是爲用戶提供'實時'完成來指導他進行有效的未來fparsec匹配。

(不生成解析此問題已在僻靜的分析界的一個名字嗎?)

+1

http://stackoverflow.com/questions/5630012/fparsec-how-to-parse-date- in-fparsec-newbie –

+0

嗨,事情是我想解析日期,而不是字符串......規則將是「下個星期五之後的下一個星期三」等。 – nicolas

+3

這不是解析 - 這是一個規則發動機。 –

回答

8

您可以定義一個簡單的領域特定語言(DSL)來表示這些類型的規則。相當於你的「解析器」的類型實際上只是一個函數,日期並返回布爾值:

type DateClassifier = DC of (DateTime -> bool) 

您可以輕鬆地定義一些簡單的功能:

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

要指定條件 - 「的下個星期五之後的星期三「 - 你需要一個助手來生成函數,這個函數可以在5日後的任何一天成功,這可以這樣完成(這有點低效,但它是使用現有基元的合成,這是不錯):

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

你的規格(或「解析」),只有成功爲您所描述的日子則是:

after DateTime.Now (wednesday <&> afterDay 5) 
+0

這正是我想到的(當然,我打算匹配一系列日期,並返回值,但這可以通過更多的組合器和一些提升來處理) – nicolas