generate multiple values during iteration

Viewed 53

Is there a way I can generate multiple values in for/list during each iteration and have the results "flattened"?

For instance:

(for/list ([i (range n)]) (values i (+ i 1)))

I'd like the result to be (list 0 1 1 2 2 3 3 4 ...).

1 Answers

This question is very much relevant to https://github.com/racket/racket/pull/2483. In the link, you will find:

  • An unmerged PR that lets you write (for/append-list ([i (range n)]) (list i (+ i 1))).
  • My proposal to let you write (for/list* ([i (range n)]) (values i (+ i 1))) (with caveat, see the link for more details).

But since these don't exist in Racket yet, the easiest way to get what you want is:

(append* (for/list ([i (range n)]) (list i (+ i 1))))
Related