JP
05/20/2020, 2:42 PMfold
? Or is a normal for
loop the only option?Jakub Pi
05/20/2020, 3:03 PMtakeWhile
before the fold.JP
05/21/2020, 5:43 AMSequence
? And thanks for the suggestion about takeWhile
. I think I’d be able to use this.Jakub Pi
05/21/2020, 7:03 AMSequence
allows you to short-circuit across operations by threading the value all the way through the sequence of operations (instead of evaluating each collection at every intermediate step), but it doesn't necessarily work inside operations such as fold, which can aggregate as well as transform. Where sequences shine is when you quit early using an operation such as .firstOrNull()
.. So operations on a Sequence
take up very little working memory, and as long as the value is not discarded the first piece of data that makes it to the end terminates the entire calculation due to the terminating condition.
As for lazy evaluation, what I'm getting at is changing the type stored inside your collection. Instead of type A
, you have an Eval<A>
(from Arrow), or in more basic Kotlin () -> A
so basically a lambda that takes no parameters and returns a value once invoked. Afraid I'm still learning this stuff so can't explain the details, but this is basically a requirement for early fold termination (unless you resort to some nasty tricks like throwing exceptions). I've seen people try to use break with a label but not successfully nor in a readable way. Check out the book Functional Programming in Kotlin, or the #functional or #arrow channels for more help on this topic.