1

I have the code

(define (add-ten s)
(let ([f (lambda(s) ((cons 10 (car (s))) (cdr (s))))])
 (f s)))

s could be a stream like powers

(define powers (letrec ([f (lambda (x) (cons x (lambda () (f (* x 2)))))]) 
(lambda  ()   (f 2))))

My function

(result-for-n-times powers 5) 

gives '(2 4 8 16 32).

Now, i want to define a stream (add-ten) that can take the stream powers and gives another stream.So, if i call it

(result-for-n-times (add-ten powers) 5)

would give '((10. 2) (10. 4) (10. 8) (10. 16) (10. 32)).

Óscar López
  • 232,561
  • 37
  • 312
  • 386
Rea
  • 67
  • 5

1 Answers1

0

Try this:

(define powers
  (letrec ([f (lambda (x)
                (cons x
                      (lambda () (f (* x 2)))))])
    (f 2)))

(define (result-for-n-times s n)
  (if (zero? n)
      '()
      (cons (car s)
            (result-for-n-times ((cdr s)) (sub1 n)))))

(define (add-ten s)
  (letrec ([f (lambda (x)
                (cons (cons 10 (car x))
                      (lambda () (f ((cdr x))))))])
    (f s)))

Notice that the add-ten procedure receives a stream as a parameter, but also it must return a stream. So letrec must be used for defining a procedure that conses each element taken from the original stream, with a promise that keeps on building the stream.

Also notice that you're not actually calling the procedure that defines powers, you either call it at the end of powers' definition or you call it like this: (powers) before passing it to add-ten. Fixing this, it works as expected:

(result-for-n-times (add-ten powers) 5)
=> '((10 . 2) (10 . 4) (10 . 8) (10 . 16) (10 . 32))
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • That was also one of my attemps so far, but gives me an error application: not a procedure; expected a procedure that can be applied to arguments given: '((10 . 2) . #) arguments...: [none] – Rea Feb 25 '13 at 14:46
  • @Rea mmm, no. the error is in `powers`. This is a correct version: `(define powers (letrec ([f (lambda (x) (cons x (lambda () (f (* x 2)))))]) (f 2)))` – Óscar López Feb 25 '13 at 14:55