Hi,
Suppose I have something like this:
(define reds (stream-cons "red" reds))
(stream-for-each displayln reds))
The output will be
red
red
red
...
What's the Racket way to make it
1 red
2 red
3 red
...
?
Hi,
Suppose I have something like this:
(define reds (stream-cons "red" reds))
(stream-for-each displayln reds))
The output will be
red
red
red
...
What's the Racket way to make it
1 red
2 red
3 red
...
?
Use for
and in-stream
:
#lang racket/base
(require racket/stream)
(define reds (stream-cons "red" reds))
(for ([red (in-stream reds)]
[idx (in-naturals 1)])
(printf "~a ~a\n" idx red))
With different output formatting, something like (guessing)
(stream-map cons (in-naturals) reds)
Except that stream-map
doesn’t have arities like map
when I checked, sadly. Is there a way to write this with stream combinators?
A few ways. Using for/stream
:
(define numbered-reds
(for/stream ([i (in-naturals)]
[r (in-stream reds)])
(cons i r))
or with SRFI-41, which has a stream-map
that accepts multiple streams:
(require srfi/41)
(define nats (stream-cons 0 (stream-map add1 nats)))
(define reds (stream-constant "red"))
(define numbered-reds (stream-map cons nats reds))
Although somewhat redundant by now:
(define numbered-reds
(for/stream ([(r i) (in-indexed (in-stream reds))])
(cons i r)))