我从CSV文件中获得一系列记录。 我想选择按日期和类型过滤这些记录,并可以选择合并符合特定条件的记录。 可以使用Seq.filter直接筛选日期和类型。 不过,我想选择合并符合特定条件的记录。 我有功能工作,我只是不知道如何可选地将其应用于结果序列。 我无法使用Seq.filter,因为整合操作不是一次一个项目的整个序列。 我可以用一个中间变量解决它,我只是想知道是否有一种优雅的惯用方式来处理这个问题。
基本上我想知道一种方法来有条件地应用一个(或多个)部分链的前进管道序列。
这是我想要的伪代码( 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 |> consolidateRecordsI get a sequence of records from a CSV file. I want to optionally filter those records by date and type and optionally consolidate records meeting certain criteria. Optionally filtering by date and type is straightforward using Seq.filter. However I would like to optionally consolidate records meeting certain criteria. I have the function working, I just can't figure out how to optionally apply it to the resulting sequence. I can't use Seq.filter because consolidate operates on the entire sequence not on one item at a time. I can solve it with an intermediate variable, I was just wondering if there was a graceful idiomatic way to handle this.
Basically I want to know a way to conditionally apply one (or more) parts of the chain in a forward pipe sequence.
This is what I want in pseudo code (options holds command line parameters):
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最满意答案
您可以在else子句中使用带有标识函数的if ... else表达式:
let x = getRecords options.filePath |> (* ... bunch of stuff ... *) |> (if options.ConsolidateRecords then consolidateRecords else id) |> (* ... optionally more stuff ... *)You can use an if ... else expression with the identity function in else clause:
let x = getRecords options.filePath |> (* ... bunch of stuff ... *) |> (if options.ConsolidateRecords then consolidateRecords else id) |> (* ... optionally more stuff ... *)更多推荐
发布评论