2013-07-23 37 views
4

我得到的記錄從CSV文件的序列。我想選擇按日期和類型過濾這些記錄,並可以選擇合併符合特定條件的記錄。可以使用Seq.filter直接篩選日期和類型。不過,我想選擇合併符合特定條件的記錄。我有功能工作,我只是不知道如何可選地將其應用於結果序列。我不能使用Seq.filter因爲在鞏固一次操作的整個序列不是一個項目。我可以用一箇中間變量解決這個問題,我只是想知道是否有處理這個優美的慣用方式。在F#去路管鏈有條件地適用於過濾器?

基本上我想知道的方式來有條件地應用鏈中的一個(或多個)部分的去路管序列。

這就是我想要的僞代碼(options持有命令行參數):

let x = 
    getRecords options.filePath 
    |> Seq.filter (fun r -> if options.Date.HasValue then 
          r.Date.Date = options.Date.Value.Date else true) 
    |> Seq.filter (fun r -> if not(String.IsNullOrEmpty(options.Type)) then 
          r.Type = options.Type else true) 
    if options.ConsolidateRecords then 
     |> consolidateRecords 

回答

7

您可以使用if ... else表達與身份功能else條款:

let x = 
    getRecords options.filePath 
    |> (* ... bunch of stuff ... *) 
    |> (if options.ConsolidateRecords then consolidateRecords else id) 
    |> (* ... optionally more stuff ... *) 
5

我會做類似

let x = 
    getRecords options.filePath 
    |> Seq.filter (fun r -> if options.Date.HasValue then 
          r.Date.Date = options.Date.Value.Date else true) 
    |> Seq.filter (fun r -> if not(String.IsNullOrEmpty(options.Type)) then 
          r.Type = options.Type else true) 
    |> fun x -> 
     if options.ConsolidateRecords then x |> consolidateRecords 
     else .... 
+0

我喜歡它。所以,什麼都不做的時候'options.ConsolidateRecords'是假,那麼else子句將只返回'x'?還是你有其他想法? – User

+2

在我對此贊成之前,你是否想拍攝7777分數的截圖?我感覺糟糕upvoting它大聲笑 – User

+0

@用戶或者返回x或繼續處理,無論你會做其他事情。 – mydogisbox

3

你也可以影射x的前一個定義:

let x = 
    getRecords options.filePath 
    |> Seq.filter (fun r -> 
     not options.Date.HasValue || r.Date.Date = options.Date.Value.Date) 
    |> Seq.filter (fun r -> 
     String.IsNullOrEmpty(options.Type) || r.Type = options.Type) 
let x = if options.ConsolidateRecords then consolidateRecords x else x