Conditionally apply a filter in a direct pipeline circuit in F #?

I get a sequence of records from a CSV file. I want to optionally filter these records by date and type, and possibly consolidate records that meet certain criteria. Optional filtering by date and type is done using Seq.filter . However, I would like to further combine records that meet certain criteria. I have a working function, I just can’t understand how it can be applied to the resulting sequence. I cannot use Seq.filter because consolidation does not work one sequence at a time in the whole sequence. I can solve it with an intermediate variable, I'm just wondering if there was an elegant idiomatic way to handle this.

Basically, I want to know how to conditionally apply one (or more) parts of a chain in a straight pipe sequence.

This is what I want in the pseudocode ( options contains command line 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 
+4
source share
3 answers

You can use the if ... else expression with the identity function in else :

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

I would do something like

 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 .... 
+5
source

You can also hide the previous definition of 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 
+3
source

Source: https://habr.com/ru/post/1493070/


All Articles