Is there a way to abort early (break) while using ...
# getting-started
j
Is there a way to abort early (break) while using
fold
? Or is a normal
for
loop the only option?
j
If you want to early terminate from your fold you are basically looking to use lazy evaluation. This will affect your API slightly.
Depending on your use-case you might be able to use something like
takeWhile
before the fold.
j
@Jakub Pi By lazy evaluation, do you mean something like using
Sequence
? And thanks for the suggestion about
takeWhile
. I think I’d be able to use this.
j
A
Sequence
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.
👍 1
768 Views