2 ms·
It's not ideal, but there's plenty of stuff that looks like this in reality. Personally, I favour Haskell's unfoldr http://hackage.haskell.org/package/base-4.8
by moomin 11y ago
It's not ideal, but there's plenty of stuff that looks like this in reality.
Personally, I favour Haskell's unfoldr http://hackage.haskell.org/package/base-4.8.1.0/docs/Data-List.html#v:unfoldr http://hackage.haskell.org/package/base-4.8.1.0/docs/Data-Li... which both doesn't require the output to be the same as the intermediate values and cleanly supports termination.
(There's actually a very good reason Haskell cares about termination: it means you can be precise about side-effects. With a classic lazy list, any side effects caused by it are determined by how many items you actually evaluate.)
- kazinator 11y agoI've looked at this before; I decided to implement it finally, calling it expand-right. (I use the "reduce" terminology rather than "fold", so the antonym has to be consistent). With explicit lambdas, decrement from 5 to zero, not including it in list: 1> (expand-right (lambda (item) (if (zerop item) nil (cons item (pred item)))) 5) (5 4 3 2 1) Using functional combinators: 2> [expand-right [iff zerop false [callf cons identity pred]] 5] (5 4 3 2 1) Include zero; bit of a mouthful: 1> [expand-right [iff null nilf [callf cons identity [iff zerop nilf pred]]] 5] (5 4 3 2 1 0) Though it can do it, it doesn't look like a great interface when inclusion of the last element is required. Comparison with the inclusive iterate (which I did implement and called "ginterate"--thanks for the nice name: 1> [ginterate [chain zerop not] pred 5] (5 4 3 2 1 0)