Streams in Scheme - stream

How does the following process work:
(define integers
(cons-stream 1
(stream-map (lambda (x) (+ x 1))
integers))

The important thing to realize here that only those expressions are evaluated which are neccessary to calculate the element of the list you're accessing.
So when you access the first element, it evaluates the first argument to cons-stream which is 1.
When you access the second element, it evaluates the first element of stream-map (lambda (x) (+ x 1)) integers. For that it needs to get the first element of integers which is 1 and then adds 1 to that and you get 2.
When you access the third element, it evaluates the second element of stream-map (lambda (x) (+ x 1)) integers. So it takes the second element of integers (2) and adds 1 to that to get 3. And so on.

Related

SICP Streams (Scheme) - CDR into the implicit stream of ones

(define ones (cons-stream 1 ones))
(stream-cdr ones)
returns an infinite sequence of evaluated 1s - i.e. I get
;Value: #0={1 1 1 1 1 1 1 and so on... - not the symbolic {1 1 ...} I would expect ...
On the other end if I define ints and cdr into it,
(define ints (cons-stream 1 (stream-map + ones ints)))
(stream-cdr ints)
I obtain the expected {1 2 ...}
Can anyone explain me why? I expect the stream-map definition to be not too far from
(define (mystream-map proc . argstreams)
(if (stream-null? (car argstreams))
the-empty-stream
(cons-stream
(apply proc (map stream-car argstreams))
(apply mystream-map (cons proc (map stream-cdr argstreams))))))
which I defined in ex 3.50 and returns the same result ... but this seems to (via (map stream-cdr argstreams)) stream-cdr into ones, which I would expect to result in the infinite sequence I get above!
Even though, if I understand correctly, due to cons-stream being a macro the second part inside the stream-map will only be lazily evaluated, at some point while I cdr into the ints stream I would expect to have to cdr into ones as well.. which instead doesn't seem to be happening! :/
Any help in understanding this would be very much appreciated!
(I also didn't override any scheme symbol and I'm running everything in MIT Scheme - Release 11.2 on OS X.)
(define ones (cons-stream 1 ones))
(stream-cdr ones)
returns an infinite sequence of evaluated ones.
No it does not. (stream-cdr ones) = (stream-cdr (cons-stream 1 ones)) = ones. It is just one ones, not the sequence of ones.
And what is ones?
Its stream-car is 1, and its stream-cdr is ones.
Whose stream-car is 1, and stream-cdr is ones again.
And so if you (stream-take n ones) (with an obvious implementation of stream-take) you will receive an n-long list of 1s, whatever the (non-negative) n is.
In other words, repeated cdring into ones produces an unbounded sequence of 1s. Or symbolically, {1 1 1 ...} indeed.
After your edit it becomes clear the question is about REPL behavior. What you're seeing most probably has to do with the difference between sharing and recalculation, just like in letrec with the true reuse (achieved through self-referring binding) vs. the Y combinator with the recalculation ((Y g) == g (Y g)).
You probably can see the behavior you're expecting, with the re-calculating definition (define (onesF) (cons-stream 1 (onesF))).
I only have Racket, where
(define ones (cons-stream 1 ones))
(define (onesF) (cons-stream 1 (onesF)))
(define ints (cons-stream 1 (stream-map + ones ints)))
(stream-cdr ones)
(stream-cdr (onesF))
(stream-cdr ints)
prints
(mcons 1 #<promise>)
(mcons 1 #<promise>)
(mcons 2 #<promise>)
Furthermore, having defined
(define (take n s)
(if (<= n 1)
(if (= n 1) ; prevent an excessive `force`
(list (stream-car s))
'())
(cons (stream-car s)
(take (- n 1)
(stream-cdr s)))))
we get
> (display (take 5 ones))
(1 1 1 1 1)
> (display (take 5 (onesF)))
(1 1 1 1 1)
> (display (take 5 ints))
(1 2 3 4 5)

delete! function for R5RS

I'm trying to write a delete! function that mutates a list and removes from it a specified value. This is the code I have so far.
(define (extend! l . xs)
(if (null? (cdr l))
(set-cdr! l xs)
(apply extend! (cdr l) xs)))
(define (delete! lis y)
(define returnLis '())
(for-each (lambda(x) (if(not(eq? x y))
(extend! returnLis x))) lis)
returnLis)
The problem I am having is that I am trying to add to an empty list which can't be done in Scheme.
Desired outcome:
(delete! '(1 2 3 4 5) 3)
=> (1 2 4 5)
Your extend function use actually would make a copy of each element in a fresh pair, but since the initial value is '() it cannot be set-cdr!. The whole point of mutating something is that old variables will continue point to the changed data and making a copy won't do that.
You need to see the pairs. You want to remove 3
[1,-]->[2,-]->[3,-]->[4,-]->[5,-]->()
So When you have found 3, you need to change the cdr of the pair that holds 2 and pint it the pair that holds 3s cdr like this:
[1,-]->[2,-]->[4,-]->[5,-]->()
Something like this then:
(define (delete lst e)
(if (and (not (null? lst)) (not (null? (cdr lst))))
(if (equal? (cadr lst) e)
(set-cdr! lst (cddr lst))
(delete (cdr lst) e))
'undefined))
(define test (list 1 2 3 4 5))
(delete lst 3)
lst ; ==> (1 2 4 5)
Notice I'm using list since a quoted literal cannot be used here since you are not allowed to change constant data like '(1 2 3 4 5). The result will be undefined or it will signal an error.
It won't work if the element in question is the first. It's because the variable points to the first pair and this only changes the pointers in pairs, not bindings. One could just switch the two first and delete the second, but in the event you have a one element list you are still stuck. Scheme implementations of mutable queues usually have a head consisting of a dummy element not considered part of the list to delete the first element.
All you need is a head-sentinel technique:
(define (delete! lis y)
(define returnLis (list 1))
(for-each (lambda(x) (if(not(eq? x y))
(extend! returnLis x))) lis)
(cdr returnLis))
Well, not all... because as it is, this is a quadratic algorithm. It re-searches the returnLis from top anew while adding each new element with extend!. Better just maintain the last cdr cell and update it:
(define (delete! lis y)
(define returnLis (list 1))
(define last-cell returnLis)
(for-each (lambda(x) (cond ((not(eq? x y))
; (extend! last-cell x)
(set-cdr! last-cell (list x))
(set! last-cell (cdr last-cell)))))
lis)
(cdr returnLis))
But, as #Sylwester points out, with this approach you shouldn't use an exclamation mark in the name, as this will return a freshly built list instead of mutating the argument's structure.

How does this implementation of a stream work?

I'm totally new to Scheme, functional programming, and specifically streams. What are the first five integers in the following stream?
(define (mystery x y z)
(cons x
(lambda ()
(mystery y z (+ x y z)))))
(mystery 1 2 3)
How does this work, and how can I use it in Racket?
We can examine the contents of an infinite stream by implementing a procedure that consumes a given number of elements and returns them in a list, for example:
(define (print strm n)
(if (zero? n)
'()
(cons (car strm)
(print ((cdr strm)) (sub1 n)))))
If we apply it to your stream, here's what we obtain:
(print (mystery 1 2 3) 5)
=> '(1 2 3 6 11)
Although in this case, it'll be more useful if we try to understand what's happening under the hood. In the end, this is just a series of procedure invocations, if we take note of the parameters that get passed at each call it's easy to find the answer. Take a look at the first column in the following table, and remember that the stream is being built by consing all the x's:
x y z
--------
1 2 3
2 3 6
3 6 11
6 11 20
11 20 37
This returns a list consisting of a number and a function. The function is - after the first call - the same as you'd get by calling (mystery 2 3 6)
How does it work? cons just makes a list of its two arguments, which in this case are a value and the result of evaluating a lambda function, which is itself a function

SICP Infinite Streams (Chapter 3.5.2)

This is a question related to the SICP Book Chapter 3.5.2.
I'm implementing a stream data structure in other programming languages. And I'm not sure if I understand the following snippet correctly.
(define (integers-starting-from n)
(cons-stream n (integers-starting-from (+ n 1))))
(define integers (integers-starting-from 1))
From what I understood at (integers-starting-from (+ n 1)) will execute the function which return a value by executing(cons-stream n (integers-starting-from (+ n 1)))). Because the second formal parameter of the cons-stream is (integers-starting-from (+ n 1)), and because it is enclosed by( ), thus it will execute the function again and again infinitely instead of delaying the execution.
From what I see before executing this snippet, It seems that the following integer will leads to an infinite recursive before even the seconds element of the stream being executed.
Why does this seems to work for scheme as shown during the lecture?
From my understand it should be written something like this instead:
(define (integers-starting-from n)
(cons-stream n (lambda() (integers-starting-from (+ n 1)))))
(define integers (integers-starting-from 1))
Does this means that scheme has some kinds of magic that delay the execution of (integers-starting-from (+ n 1)) ?
Thank you in advance
The trick lies in how we implement cons-stream. You explicitly created an evaluation promise when you defined the (lambda () ...) thunk. The special form cons-stream does this, but implicitly and using Scheme's primitives. For example, it can be implemented like this, notice how we use delay:
(define-syntax stream-cons
(syntax-rules ()
((stream-cons head tail)
(cons head (delay tail)))))
It makes more sense to encapsulate all the promise-creation logic in a single place, say cons-stream, instead of explicitly creating thunks everywhere.

Scheme console printing

Just started with Scheme. I'm having problem with printing on console.
A simple list printing example:
(define factorial
(lambda (n)
(cond
((= 0 n) 1)
(#t (* n (factorial (- n 1)))))))
I want to print n, every time the function is called. I figured that I can't do that within the same function? Do I need to call another function just so I can print?
Printing in Scheme works by calling display (and possibly, newline).
Since you want to call it sequentially before/after something else (which, in a functional (or in the case of Scheme, functional-ish) language only makes sense for the called functions side-effects), you would normally need to use begin, which evaluates its arguments in turn and then returns the value of the last subexpression. However, lambda implicitly contains such a begin-expression.
So in your case, it would go like this:
(lambda (n)
(display n) (newline)
(cond [...]))
Two remarks:
You can use (define (factorial n) [...]) as a shorthand for (define factorial (lambda (n) [...])).
The way you implement factorial forbids tail call-optimization, therefore the program will use quite a bit of stack space for larger values of n. Rewriting it into a optimizable form using an accumulator is possible, though.
If you only want to print n once, when the user calls the function, you will indeed need to write a wrapper, like this:
(define (factorial n)
(display n) (newline)
(inner-factorial n))
And then rename your function to inner-factorial.

Resources