2011-05-02 26 views
0

我有一個數組包含日期沒有周末(不一定是工作日)。現在我只想每個月只有一個日期,並且只能從某一天開始。如果數組中不存在該日期,則應在結果列表中顯示以下現有日期。給定數組:1.2.2010,2.2.2010,5.2.2010,6.2.2010,...,1.3.2010,2.3.2010,...,1.4.2010,4.4。給定數組: 2010f中的過濾日期數組#

我希望所有二號每個月的日期

結果:2010年2月2日,2010年3月2日,2010年4月4日

我該怎麼做,在F#?請提供一個教育和很好的解決方案,我嘗試學習F#。我知道如何以命令的方式做到這一點:)

謝謝! :d

回答

1

這裏是一個可能的解決方案:

// Your input list with dates 
let input = [DateTime.Now] 
// We want 2nd day or later 
let number = 2 

input 
    // First, create group of dates for every Year/Month 
    // (so that all days in specifc month are in a single group) 
    |> Seq.groupBy (fun dt -> dt.Year, dt.Month) 
    |> Seq.map (fun ((y, m), dates) -> 
    // We want only dates that are later (or equal to) this 'limit' 
    let limit = new DateTime(y, m, number) 
    // Remove dates before the limit and then select minimal date 
    dates |> Seq.filter (fun d -> d >= limit) |> Seq.min) 
1

這裏的另一個(假定排序輸入):

type DateTime = System.DateTime 

let filterDayOrFollowing day (input:DateTime[]) = 
    (input, ([], None)) 
    ||> Array.foldBack (fun date (acc, following:DateTime option) -> 
     if date.Day = day then date::acc, None 
     else match following with 
      | Some f when date.Year = f.Year 
         && date.Month = f.Month 
         && date.Day < day -> f::acc, None 
      | _ -> acc, Some date) 
    |> fst 

let expected = [ DateTime(2010, 2, 2) 
       DateTime(2010, 3, 2) 
       DateTime(2010, 4, 4) ] 

let actual = 
    [| DateTime(2010, 2, 1) 
     DateTime(2010, 2, 2) 
     DateTime(2010, 2, 5) 
     DateTime(2010, 2, 6) 
     DateTime(2010, 3, 1) 
     DateTime(2010, 3, 2) 
     DateTime(2010, 4, 1) 
     DateTime(2010, 4, 4) |] 
    |> filterDayOrFollowing 2 

actual = expected |> printfn "actual = expected: %b"