Hello!
I was solving this issue, and it got me wondering if there is a better
solution somewhere in the library. Could you check this out?
I want to find consecutive runs of numbers and replace them with a sum, while
preserving all other objects in the sequence (currently only strings are in
there). For example:
IN: { 1 5 "hello" 2 "world" 3 6 9 "!" } collapse-numbers
OUT: { 6 "hello" 2 "world" 18 "!" }
Here's the `collapse-numbers` implementation that I came up with:
:: collapse-numbers ( seq -- seq' )
f :> accum! seq [
accum 2dup [ number? ] both? [
+ accum! f
] [
swap accum!
] if
] map sift accum suffix ;
Using a local variable for a side-effect in map feels like cheating, straight
from my imperative programming background.
Is there a way to, maybe, convert numbers into subsequences?
IN: { 1 5 "hello" 2 "world" 3 6 9 "!" } [ number? ] map-runs
OUT: { { 1 5 } "hello" { 2 } "world" { 3 6 9 } "!" }
If we had something like `map-runs`, the whole task could be solved in a more
functional way:
: collapse-numbers ( seq -- seq' )
[ number? ] map-runs [ dup string? [ sum ] unless ] map ;
What are your thoughts on this? Do we **have** something like `map-runs`? Do
we **need** it? Should I have used PEGs to parse the sequence?
---=====---
Александр
------------------------------------------------------------------------------
Check out the vibrant tech community on one of the world's most
engaging tech sites, SlashDot.org! http://sdm.link/slashdot
_______________________________________________
Factor-talk mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/factor-talk