在F#中有条件地应用前向管道链中的过滤器?(Conditionally apply filter in forward pipe chain in F#?)

编程入门 行业动态 更新时间:2024-10-27 00:30:21
在F#中有条件地应用前向管道链中的过滤器?(Conditionally apply filter in forward pipe chain in F#?)

我从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

I 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 ... *)

更多推荐

本文发布于:2023-08-01 01:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1351449.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中有   过滤器   前向   管道   条件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!