Use*_*ser 4 f# conditional-statements
我从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
|> consolidateRecords
Run Code Online (Sandbox Code Playgroud)
您可以if ... else在else子句中使用带有identity函数的表达式:
let x =
getRecords options.filePath
|> (* ... bunch of stuff ... *)
|> (if options.ConsolidateRecords then consolidateRecords else id)
|> (* ... optionally more stuff ... *)
Run Code Online (Sandbox Code Playgroud)
我会做点什么的
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 ....
Run Code Online (Sandbox Code Playgroud)