Vortca 2
Vortca 2

Reputation: 41

Generate stream in racket

I'm trying to generate a stream in racket that contains a sequence of 1 or 2 element lists. It should start with the number one in a list and every subsequent element of the stream is incremented by one with the added requirement of even numbers should be duplicated in the list. For example: ((1)(2 2)(3)(4 4)(5)(6 6))

How would I be able to do that?

Upvotes: 0

Views: 539

Answers (3)

Shawn
Shawn

Reputation: 52344

I don't see for/stream used often, but it can make this really simple to do all in one call:

#lang racket/base

(require racket/stream)

(define strm
  (for/stream ([n (in-naturals 1)])
    (if (even? n)
        (list n n)
        (list n))))

(println (stream->list (stream-take strm 6)))

Upvotes: 0

user5920214
user5920214

Reputation:

Write a function, sc, say, which takes one argument, n say. It should return:

  • if its argument is even (stream-cons (list n n) (sc (+ n 1)));
  • if its argument is odd (stream-cons (list n) (sc (+ n 1))).

(sc 1) is the stream you want.

Upvotes: 2

Atharva Shukla
Atharva Shukla

Reputation: 2137

It's a 2-step process:

  1. Create stream like 1, 2, 3, 4. ... using in-range or in-naturals
  2. Map over each element to transform them into lists with stream-map

This code snippet shows a way to create infinite as well as bounded "even-odd" lazy streams:

#lang racket

; (-> Nat (U (list Nat Nat) (list Nat)))
; a pair of `nat` if nat is even, singleton list otherwise
(define (nat->stream-elem nat)
  (if (even? nat) (list nat nat) (list nat)))

; (->* () (Nat) (stream-of (U (list Nat Nat) (list Nat))))
; a stream with `total`, infinite stream if no arg provided
(define (even-odd-stream [total false])
  (stream-map nat->stream-elem (if total (in-range 1 (+ total 1)) (in-naturals 1))))

; (-> Nat Void)
; displays first `to-display` elements from `stream`
(define (display-stream to-display stream)
  (for ([i to-display] [e stream])
    (displayln e)))


; Displays all 6 elements of a 6-element even-odd-stream
(display-stream 6 (even-odd-stream 6))

(displayln "- - -")

; Displays first 10 elements of an infinite even-odd-stream
(display-stream 10 (even-odd-stream))

Upvotes: 2

Related Questions