I have two Racket programming homework questions:
The first one: Write a function kth-item that takes two arguments, the first is a stream s and the second is a number k, and it produces the result of extracting k elements from the stream, returning only the last element. Very similar to the previous one, but only returns a single element. You may assume k is greater than 0.
The second one: Write a stream negate-2-and-5 that is like the stream of natural numbers (i.e., 1, 2, 3, ...) except that numbers divisible by 2 or 5 are negated (i.e., 1, -2, 3, -4, -5, -6, 7, -8, 9, -10, 11, -12, 13, -14, ...). Remember a stream is a thunk that when called produces a pair, where the car of the pair is the next number and the cdr will be the continuation of the stream.
For first questions I know how to get the list of ith but I have not idea how to continues to get the last element.
For second questions, I know how to get either 2 or 5 works, but I have not idea how to combine them, so both 2 and 5 can work at the same time.
(define (next-k-items s k)
(if (<= k 0)
empty
(cons (car (s))
(next-k-items (cdr (s)) (- k 1)))))
(define (negate-2-and-5)
(define (f x) (cons (if (= 0 (remainder x 5)) (- x) x)
(lambda () (f (+ x 1)))))
(f 1))
Here are the testing codes:
(check-expect (kth-item nats 3) 3)
(check-expect (next-k-items negate-2-and-5 7) '(1 -2 3 -4 -5 -6 7))