is there a nice alternative for the following? ``...
# advent-of-code
e
is there a nice alternative for the following?
Copy code
// s is my input representation and once a portion is processed, I remove that portion

val sub = mutableListOf<Packet>()

while(!s.isEmpty()) {
   sub.add(processPacket(s))
}

return sub
looking for something similar to
fold
but with an exit condition
e
First, you’ll have to get rid of mutation you do inside
processPacket
One you’ve transformed it into pure functions, you can start looking for nicer functional alternatives.
But, frankly, recursive descent is much easier to write with mutable data structures. However, you don’t need to remove anything. The only mutable thing you need is something that keeps your current position or iterator into the next thing to process.
e
yeah. But I ended up parsing my input string to an
ArrayDeque
so I don’t have to trace the current position, I’m always at the head
e
I did String.iterator(), wrapped CharIterator -> BoolIterator, and implemented BoolIterator.take()
no need for the whole expanded bit sequence to ever exist in memory :)
m
generateSequence { if (s.isEmpty()) null else processPacket(s) }.toList()
👍 2
n
or
return buildList { while (s.isNotEmpty()) add(processPacket(s)) }
m
or
return mutableListOf<...>().apply { while (s.isNotEmpty()) add(processPacket(s)) }
if you still need it to be a mutable list 🙂
e
nice! I wasn’t aware of these