I want to sort and/or filter a sequence. Basically something like this:
var result = getReallyLongSeq() // returns Seq[SomeClass]
if (doFilter) {
result = result.filter( ... )
}
if (doSort) {
result = result.sortWith( ... )
}
Now, this is an obviously valid approach, but is there a more functional way of doing that?
Without library support, you can roll out your own Boolean Reader Monad.
This is functional, pure and configurable.
Boolean Reader
Here we made a wrapper for a
Boolean => Athat allows monadic composition, and it’s probably already implemented in some library, like scalaz.We’re only interested in the
runmethod, for this case, but you can get interested in other opportunities.Configured filter & sort
Then we wrap our filter and sort check with the
ReaderLifting
Now, to compose these functions, since the output is no more a simple
Seq, we need to lift one of them to work within aBoolConfNow we’re able to convert any function from
A => Bto a lifted function fromBoolConf[A] => BoolConf[B]Composing
Now we can compose functionally:
There’s more
We can also create a generic “builder” for our
mFilterandmSortYou can “sort” the sorting equivalent by yourself
Thanks are due to Runar for the inspiration