Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to "open Seq" or similar effect?

Tags:

f#

refactoring

a 
|>Seq.map fixLine 
|>Seq.map splitCells 
|>Seq.map getName 
|>Seq.where(fun a->not<|Seq.isEmpty a) 
|>Seq.map fixName

Always find it annoying while keep lots of Seq. in lines. Suggest a good way to omit them...

For example, use List.map for lists, use just map for seq, or split them into different modules when I'm using seq and lists.

a
|>map fixLine
|>map splitCells
|>map getName
|>where(fun a->not<|isEmpty a)
|>map fixName

Looks really better.

like image 505
a_a Avatar asked Feb 24 '16 17:02

a_a


2 Answers

You could also just define aliases for the functions you want:

let map = Seq.map
let where = Seq.filter

Or you could make it even more terse by defining your own operators:

let (|!>) s f = Seq.map f s
let (|*>) s f = Seq.filter f s

a
|!> fixLine
|!> splitCells
|!> getName
|*> (fun a->not<|isEmpty a)
|!> fixName

But at this point, your code becomes way too cryptic - i.e. someone looking at the code will have a hard time understanding what's going on.

And finally, you could make the original code look a bit better by noticing that a composition of maps is a map of composition:

a
|> Seq.map (fixLine >> splitCells >> getName)
|> Seq.filter (not << isEmpty)
|> Seq.map fixName

This is the solution that I personally would prefer.


In general, my personal experience shows that, despite the first impulse to "fix" the repetitiveness by making the repetitive parts themselves smaller, there is usually a better solution that would make your code not only look better, but better factored as well.

like image 90
Fyodor Soikin Avatar answered Sep 19 '22 23:09

Fyodor Soikin


I don't think there is an easy way to avoid repeating the Seq - this is just one place where F# makes things a bit more explicit (so that you know what's going on).

But you can use the F# Core Fluent library which gives you a more C#-like syntax with .:

a.map(fixLine).map(splitCells).map(getName).filter(isEmpty >> not).map(fixName)
like image 36
Tomas Petricek Avatar answered Sep 22 '22 23:09

Tomas Petricek