How to fix this error: begin (possibly implicit): no expression after a sequence of internal definitions - scheme

I'm having problems implementing one generator called fib in a function.
I want the function to return me a generator that generates the first n Fibonacci numbers.
;THIS IS MY GENERATOR
(define fib
(let ((a 0) (b 1))
(lambda ()
(let ((return a))
(set! a b)
(set! b (+ b return)
)return))))
;THIS IS MY FUNCTION
(define (take n g)
(define fib
(let ((a 0) (b 1) (cont 1))
(lambda ()
(if (>= cont n) #f
(let ((return a))
(set! cont (+ cont 1))
(set! a b)
(set! b (+ b return)
)(return)))))))
I expect a generator to return the Fibonacci numbers up to N (delivered to the function). But the actual output is :
begin (possibly implicit): no expression after a sequence of internal definitions in:
(begin
(define fib
(let ((a 0) (b 1) (cont 1))
(lambda ()
(if (>= cont n) #f
(let ((return a))
(set! cont (+ cont 1))
(set! a b)
(set! b (+ b return))
(return)))))))

Just as the error says, you have no expressions in your function's definition except for some internal definition (which, evidently, is put into an implicit begin). Having defined it, what is a function to do?
More importantly, there's problems with your solution's overall design.
When writing a function's definition, write down its sample calls right away, so you see how it is supposed / intended / to be called. In particular,
(define (take n g)
suggests you intend to call it like (take 10 fib), so that inside take's definition g will get the value of fib.
But fib is one global generator. It's not restartable in any way between different calls to it. That's why you started copying its source, but then realized perhaps, why have the g parameter, then? Something doesn't fit quite right, there.
You need instead a way to create a new, fresh Fibonacci generator when you need to:
(define (mk-fib)
(let ((a 0) (b 1))
(lambda ()
(let ((ret a))
(set! a b)
(set! b (+ ret b))
ret)))) ;; ..... as before .....
Now each (mk-fib) call will create and return a new, fresh Fibonacci numbers generator, so it now can be used as an argument to a take call:
(define (taking n g) ;; (define q (taking 4 (mk-fib)))
Now there's no need to be defining a new, local copy of the same global fib generator, as you were trying to do before. We just have whatever's specific to the take itself:
(let ((i 1))
(lambda () ; a generator interface is a function call
(if (> i n) ; not so good: what if #f
#f ; is a legitimately produced value?
(begin
(set! i (+ i 1))
(g)))))) ; a generator interface is a function call
Now we can define
> (define q (taking 4 (mk-fib)))
> (q)
0
> (q)
1
> (q)
1
> (q)
2
> (q)
#f
> (q)
#f
>

Related

Why does let not allow mutually recursive definitions, whereas letrec can?

I suspect that I fundamentally misunderstand Scheme's evaluation rules. What is it about the way that let and letrec are coded and evaluated that makes letrec able to accept mutually recursive definitions whereas let cannot? Appeals to their basic lambda forms may be helpful.
The following is even? without let or letrec:
(define even?
( (lambda (e o) <------. ------------.
(lambda (n) (e n e o)) -----* |
) |
(lambda (n e o) <------. <---+
(if (= n 0) #t (o (- n 1) e o))) -----* |
(lambda (n e o) <------. <---*
(if (= n 0) #f (e (- n 1) e o))))) -----*
This defines the name even? to refer to the result of evaluating the application of the object returned by evaluating the (lambda (e o) (lambda (n) (e n e o)) ) expression to two objects produced by evaluating the other two lambda expressions, the ones in the arguments positions.
Each of the argument lambda expressions is well formed, in particular there are no references to undefined names. Each only refers to its arguments.
The following is the same even?, written with let for convenience:
(define even?-let-
(let ((e (lambda (n e o) <------. <---.
(if (= n 0) #t (o (- n 1) e o)))) -----* |
(o (lambda (n e o) <------. <---+
(if (= n 0) #f (e (- n 1) e o)))) -----* |
) |
(lambda (n) (e n e o)) )) ----------------------------*
But what if we won't pass those e and o values around as arguments?
(define even?-let-wrong- ^ ^
(let ((e (lambda (n) <-----------------|--|-------.
(if (= n 0) #t (o (- n 1))))) --* | |
(o (lambda (n) | |
(if (= n 0) #f (e (- n 1))))) --* |
) |
(lambda (n) (e n)) )) ---------------------------*
What are the two names o and e inside the two lambda's if expressions refer to now?
They refer to nothing defined in this piece of code. They are "out of scope".
Why? It can be seen in the equivalent lambda-based expression, similar to what we've started with, above:
(define even?-wrong- ^ ^
( (lambda (e o) <----. ----|---|---------.
(lambda (n) (e n)) --* | | |
) | | |
(lambda (n) | | <------+
(if (= n 0) #t (o (- n 1)))) ---* | |
(lambda (n) | <------*
(if (= n 0) #f (e (- n 1)))))) -----*
This defines the name even?-wrong- to refer to the result of evaluating the application of the object returned by evaluating the (lambda (e o) (lambda (n) (e n)) ) expression to two objects produced by evaluating the other two lambda expressions, the ones in the arguments positions.
But each of them contains a free variable, a name which refers to nothing defined in its scope. One contains an undefined o, and the other contains an undefined e.
Why? Because in the application (<A> <B> <C>), each of the three expressions <A>, <B>, and <C> is evaluated in the same scope -- that in which the application itself appears; the enclosing scope. And then the resulting values are applied to each other (in other words, the function call is made).
A "scope" is simply a textual area in a code.
Yet we need the o in the first argument lambda to refer to the second argument lambda, not anything else (or even worse, nothing at all). Same with the e in the second argument lambda, which we need to point at the first argument lambda.
let evaluates its variables' init expressions in the enclosing scope of the whole let expression first, and then it creates a fresh environment frame with its variables' names bound to the values which result from those evaluations. The same thing happens with the equivalent three-lambdas expression evaluation.
letrec, on the other hand, first creates the fresh environment frame with its variables' names bound to as yet-undefined-values (such that referring to those values is guaranteed to result in an error) and then it evaluates its init expressions in this new self-referential frame, and then it puts the resulting values into the bindings for their corresponding names.
Which makes the names inside the lambda expressions refer to the names inside the whole letrec expression's scope. In contrast to the let's referring to the outer scope:
^ ^
| |
(let ((e | |
(... o ...)) |
(o |
(............ e .........)))
.....)
does not work;
.----------------.
| |
(letrec ((e <--|--------. |
(..... o ...)) | |
(o <-----------|-------*
(.............. e .........)))
.....)
works fine.
Here's an example to further clarify things:
1. consider ((lambda (a b) ....here a is 1.... (set! a 3) ....here a is 3....) 1 2)
now consider ((lambda (a b) .....) (lambda (x) (+ a x)) 2).
the two as are different -- the argument lambda is ill-defined.
now consider ((lambda (a b) ...(set! a (lambda (x) (+ a x))) ...) 1 2).
the two as are now the same.
so now it works.
let can't create mutually-recursive functions in any obvious way because you can always turn let into lambda:
(let ((x 1))
...)
-->
((λ (x)
...)
1)
and similarly for more than one binding:
(let ((x 1)
(y 2))
...)
-->
((λ (x y)
...)
1 2)
Here and below, --> means 'can be translated into' or even 'could be macroexpanded into'.
OK, so now consider the case where the x and y are functions:
(let ((x (λ (...) ...))
(y (λ (...) ...)))
...)
-->
((λ (x y)
...)
(λ (...) ...)
(λ (...) ...))
And now it's becoming fairly clear why this can't work for recursive functions:
(let ((x (λ (...) ... (y ...) ...))
(y (λ (...) ... (x ...) ...)))
...)
-->
((λ (x y)
...)
(λ (...) (y ...) ...)
(λ (...) (x ...) ...))
Well, let's make this more concrete to see what goes wrong: let's consider a single recursive function: if there's a problem with that then there certainly will be problems with sets of mutually recursive functions.
(let ((factorial (λ (n)
(if (= n 1) 1
(* n (factorial (- n 1)))))))
(factorial 10))
-->
((λ (factorial)
(factorial 10))
(λ (n)
(if (= n 1) 1
(* n (factorial (- n 1))))))
OK, what happens when you try to evaluate the form? We can use the environment model as described in SICP . In particular consider evaluating this form in an environment, e, in which there is no binding for factorial. Here's the form:
((λ (factorial)
(factorial 10))
(λ (n)
(if (= n 1) 1
(* n (factorial (- n 1))))))
Well, this is just a function application with a single argument, so to evaluate this you simply evaluate, in some order, the function form and its argument.
Start with the function form:
(λ (factorial)
(factorial 10))
This just evaluates to a function which, when called, will:
create an environment e' which extends e with a binding of factorial to the argument of the function;
call whatever is bound to factorial with the argument 10 and return the result.
So now we have to evaluate the argument, again in the environment e:
(λ (n)
(if (= n 1) 1
(* n (factorial (- n 1)))))
This evaluates to a function of one argument which, when called, will:
establish an environment e'' which extends e with a binding of n to the argument of the function;
if the argument isn't 1, will try to call some function bound to a variable called factorial, looking up this binding in e''.
Hold on: what function? There is no binding of factorial in e, and e'' extends e (in particular, e'' does not extend e'), but by adding a binding of n, not factorial. Thus there is no binding of factorial in e''. So this function is an error: you will either get an error when it's evaluated or you'll get an error when it's called, depending on how smart the implementation is.
Instead, you need to do something like this to make this work:
(let ((factorial (λ (n) (error "bad doom"))))
(set! factorial
(λ (n)
(if (= n 1) 1
(* n (factorial (- n 1))))))
(factorial 10))
-->
((λ (factorial)
(set! factorial
(λ (n)
(if (= n 1) 1
(* n (factorial (- n 1))))))
(factorial 10))
(λ (n) (error "bad doom")))
This will now work. Again, it's a function application, but this time all the action happens in the function:
(λ (factorial)
(set! factorial
(λ (n)
(if (= n 1) 1
(* n (factorial (- n 1))))))
(factorial 10))
So, evaluating this in e results in a function which, when called will:
create an environment e', extending e, in which there is a binding of factorial to whatever its argument is;
mutate the binding of factorial in e', assigning a different value to it;
call the value of factorial in e', with argument 10, returning the result.
So the interesting step is (2): the new value of factorial is the value of this form, evaluated in e':
(λ (n)
(if (= n 1) 1
(* n (factorial (- n 1)))
Well, this again is a function which, when called, will:
create an environent, e'', which extends e' (NOTE!) with a binding for n;
if the value of the binding of n is not 1, call whatever is bound to factorial in the e'' environment.
And now this will work, because there is a binding of factorial in e'', because, now, e'' extends e' and there is a binding of factorial in e'. And, further, by the time the function is called, e' will have been mutated so that the binding is the correct one: it's the function itself.
And this is in fact more-or-less how letrec is defined. In a form like
(letrec ((a <f1>)
(b <f2>))
...)
First the variables, a and b are bound to some undefined values (it is an error ever to refer to these values). Then <f1> and <f2> are evaluated in some order, in the resulting environment (this evaluation should not refer to the values that a and b have at that point), and the results of these evaluations are assigned to a and b respectively, mutating their bindings and finally the body is evaluated in the resulting environment.
See for instance R6RS (other reports are similar but harder to refer to as most of them are PDF):
The <variable>s are bound to fresh locations, the <init>s are evaluated in the resulting environment (in some unspecified order), each <variable> is assigned to the result of the corresponding <init>, the <body> is evaluated in the resulting environment, and the values of the last expression in <body> are returned. Each binding of a <variable> has the entire letrec expression as its region, making it possible to define mutually recursive procedures.
This is obviously something similar to what define must do, and in fact I think it's clear that, for internal define at least, you can always turn define into letrec:
(define (outer a)
(define (inner b)
...)
...)
-->
(define (outer a)
(letrec ((inner (λ (b) ...)))
...))
And perhaps this is the same as
(letrec ((outer
(λ (a)
(letrec ((inner
(λ (b)
...)))
...)))))
But I am not sure.
Of course, letrec buys you no computational power (neither does define): you can define recursive functions without it, it's just less convenient:
(let ((facter
(λ (c n)
(if (= n 1)
1
(* n (c c (- n 1)))))))
(let ((factorial
(λ (n)
(facter facter n))))
(factorial 10)))
or, for the pure of heart:
((λ (facter)
((λ (factorial)
(factorial 10))
(λ (n)
(facter facter n))))
(λ (c n)
(if (= n 1)
1
(* n (c c (- n 1))))))
This is pretty close to the U combinator, or I always think it is.
Finally, it's reasonably easy to write a quick-and-dirty letrec as a macro. Here's one called labels (see the comments to this answer):
(define-syntax labels
(syntax-rules ()
[(_ ((var init) ...) form ...)
(let ((var (λ x (error "bad doom"))) ...)
(set! var init) ...
form ...)]))
This will work for conforming uses, but it can't make referring to the initial bindings of the variables is an error: calling them is, but they can leak out. Racket, for instance, does some magic which makes this be an error.
Let's start with my version of everyone's favorite mutually recursive example, even-or-odd.
(define (even-or-odd x)
(letrec ((internal-even? (lambda (n)
(if (= n 0) 'even
(internal-odd? (- n 1)))))
(internal-odd? (lambda (n)
(if (= n 0) 'odd
(internal-even? (- n 1))))))
(internal-even? x)))
If you wrote that with let instead of letrec, you'd get an error that internal-even? in unbound. The descriptive reason for why that is is that the expressions that define the initial values in a let are evaluated in a lexical environment before the variables are bound whereas letrec creates an environment with those variables first, just to make this work.
Now we'll have a look at how to implement let and letrec with lambda so you can see why this might be.
The implementation of let is fairly straightforward. The general form is something like this:
(let ((x value)) body) --> ((lambda (x) body) value)
And so even-or-odd written with a let would become:
(define (even-or-odd-let x)
((lambda (internal-even? internal-odd?)
(internal-even? x))
(lambda (n)
(if (= n 0) 'even
(internal-odd? (- n 1))))
(lambda (n)
(if (= n 0) 'odd
(internal-even? (- n 1))))))
You can see that the bodies of internal-even? and internal-odd? are defined outside the scope of where those names are bound. It gets an error.
To deal with this problem when you want recursion to work, letrec does something like this:
(letrec (x value) body) --> ((lambda (x) (set! x value) body) #f)
[Note: There's probably a much better way of implementing letrec but that's what I'm coming up with off the top of my head. It'll give you the idea, anyway.]
And now even-or-odd? becomes:
(define (even-or-odd-letrec x)
((lambda (internal-even? internal-odd?)
(set! internal-even? (lambda (n)
(if (= n 0) 'even
(internal-odd? (- n 1)))))
(set! internal-odd? (lambda (n)
(if (= n 0) 'odd
(internal-even? (- n 1)))))
(internal-even? x))
#f #f))
Now internal-even? and internal-odd? are being used in a context where they've been bound and it all works.

How to make a list with generators in Scheme

I'm having problems with this problem because i don't know how to make a list with recursivity using generators. The idea is to create a function that receives a generator that generates n numbers and returns a list with those numbers.
This is my code
;GENERATOR THAT GENERATES "INFINITE NUMBERS OF FIBONACCI"
(define (fib)
(let ((a 0) (b 1))
(lambda ()
(let ((ret a))
(set! a b)
(set! b (+ ret b))
ret))))
;RETURNS A GENERATOR THAT GENERATES NUMBERS OF FIBONACCI UP TO N
(define (taking n g)
(let ((i 1))
(lambda ()
(if (> i n)
#f
(begin
(set! i (+ i 1))
(g))))))
Your definitions are fine! You just need to call them correctly to see it.
> (define t (taking 10 (fib)))
> (t)
0
> (t)
1
> (t)
1
> (t)
2
> (t)
3
> (t)
5
>
UPDATE
(define (generator->list n g)
(if (= n 0)
'()
(cons (g) (generator->list (- n 1) g))))
(generator->list 10 (fib))
So something like this:
(define (to-list gen)
(let loop ((l '()))
(let ((r (gen)))
(if r
(loop (cons r l))
(reverse! l)
))))
Untested. What this does is build up a list in reverse consing the truthy items. When it gets a falsy item, it stops and returns the reverse of the accumulation list.

Scheme check value if not even

I have the following function to check if a positive value is even.
(define (even? n)
(cond
((= n 0) #t)
((< n 0) #f)
(else (even? (- n 2)))
)
)
I am trying to use this function to increment a store counter when a checked value is not even (odd) using both the even? function and a logical not, but I can't seem to figure out the correct syntax.
(define (function a b)
(define (iter a b store)
(cond
((= b 1) (+ store a)
(else
(iter (double a) (halve b) (if (not (even? b)) (+ a store) store)))
)
)
(iter a b 0)
)
Could anyone check my syntax to see what I am doing wrong?
A call of (function 1 1) should return 1
A call of (fucntion 1960 56) should return 109760 but I receive 141120
EDIT:
I realize that my halve funciton must be impromperly defined. I tried to implement a halving function that used only subtraction.
(define (halve n)
(define (iter src store)
(cond
((<= src 0) store)
(else (iter (- src 2) (+ store 1)))
)
)
(iter n 0)
)
Please note that the even? function is built-in, you don't have to implement it. Now regarding the problem - this line is not doing what you think:
(if (not (even? b)) (+ a store))
That expression doesn't update the value of store, it's just evaluating the result of adding a to store and then the value obtained is lost - we didn't save it, we didn't pass it to the recursion, the result of the addition is discarded and then the next line is executed.
In Scheme, we use set! to update a variable, but that's frowned upon, we try to avoid mutation operations - and in this case it's not necessary, we only need to pass the correct value to the recursive call.
UPDATE
Now that you've made it clear that you're implementing the Ethiopian multiplication algorithm, this is how it should be done:
(define (halve n)
(quotient n 2))
(define (double n)
(* 2 n))
(define (function a b)
(define (iter a b store)
(cond
((= a 0) store)
((even? a) (iter (halve a) (double b) store))
(else (iter (halve a) (double b) (+ store b)))))
(iter a b 0))
It works as expected:
(function 1 1)
=> 1
(function 1960 56)
=> 109760
You seem to be missing a ), just before the call to iter.

Why Scheme requires apply in Y-combinator implementation, but Racket doesn't?

Here is the Y-combinator in Racket:
#lang lazy
(define Y (λ(f)((λ(x)(f (x x)))(λ(x)(f (x x))))))
(define Fact
(Y (λ(fact) (λ(n) (if (zero? n) 1 (* n (fact (- n 1))))))))
(define Fib
(Y (λ(fib) (λ(n) (if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2))))))))
Here is the Y-combinator in Scheme:
(define Y
(lambda (f)
((lambda (x) (x x))
(lambda (g)
(f (lambda args (apply (g g) args)))))))
(define fac
(Y
(lambda (f)
(lambda (x)
(if (< x 2)
1
(* x (f (- x 1))))))))
(define fib
(Y
(lambda (f)
(lambda (x)
(if (< x 2)
x
(+ (f (- x 1)) (f (- x 2))))))))
(display (fac 6))
(newline)
(display (fib 6))
(newline)
My question is: Why does Scheme require the apply function but Racket does not?
Racket is very close to plain Scheme for most purposes, and for this example, they're the same. But the real difference between the two versions is the need for a delaying wrapper which is needed in a strict language (Scheme and Racket), but not in a lazy one (Lazy Racket, a different language).
That wrapper is put around the (x x) or (g g) -- what we know about this thing is that evaluating it will get you into an infinite loop, and we also know that it's going to be the resulting (recursive) function. Because it's a function, we can delay its evaluation with a lambda: instead of (x x) use (lambda (a) ((x x) a)). This works fine, but it has another assumption -- that the wrapped function takes a single argument. We could just as well wrap it with a function of two arguments: (lambda (a b) ((x x) a b)) but that won't work in other cases too. The solution is to use a rest argument (args) and use apply, therefore making the wrapper accept any number of arguments and pass them along to the recursive function. Strictly speaking, it's not required always, it's "only" required if you want to be able to produce recursive functions of any arity.
On the other hand, you have the Lazy Racket code, which is, as I said above, a different language -- one with call-by-need semantics. Since this language is lazy, there is no need to wrap the infinitely-looping (x x) expression, it's used as-is. And since no wrapper is required, there is no need to deal with the number of arguments, therefore no need for apply. In fact, the lazy version doesn't even need the assumption that you're generating a function value -- it can generate any value. For example, this:
(Y (lambda (ones) (cons 1 ones)))
works fine and returns an infinite list of 1s. To see this, try
(!! (take 20 (Y (lambda (ones) (cons 1 ones)))))
(Note that the !! is needed to "force" the resulting value recursively, since Lazy Racket doesn't evaluate recursively by default. Also, note the use of take -- without it, Racket will try to create that infinite list, which will not get anywhere.)
Scheme does not require apply function. you use apply to accept more than one argument.
in the factorial case, here is my implementation which does not require apply
;;2013/11/29
(define (Fact-maker f)
(lambda (n)
(cond ((= n 0) 1)
(else (* n (f (- n 1)))))))
(define (fib-maker f)
(lambda (n)
(cond ((or (= n 0) (= n 1)) 1)
(else
(+ (f (- n 1))
(f (- n 2)))))))
(define (Y F)
((lambda (procedure)
(F (lambda (x) ((procedure procedure) x))))
(lambda (procedure)
(F (lambda (x) ((procedure procedure) x))))))

Iterative modulo by repeated subtraction?

I am trying to write an iterative procedure to do modulo arithmetic in scheme without using the built in procedures modulo, remainder or /. However I ran into a few problems while trying to write the code, which looks like this so far:
(define (mod a b)
(define (mod-iter a b)
(cond ((= b 0) 0)
((< b 0) (+ old_b new_b))))
(mod-iter a (- a b)))
As you can see, I ran into the problem of needing to add the original value of b to the current value of b. I am not sure how to go about that. Also, when i left the second conditional's answer to be primitive data (just to make sure the enitre procedure worked), I would get an "unspecified return value" error, and I'm not sure why it happens because the rest of my code loops (or so it seems?)
Thank you in advance for any insight to this.
When you define your mod-iter function with arguments (a b) you are shadowing the arguments defined in mod. To avoid the shadowing, use different identifiers, as such:
(define (mod a b)
(define (mod-iter ax bx)
(cond ((= bx 0) 0)
((< bx 0) (+ b bx))))
(mod-iter a (- a b)))
Note, this doesn't look like the proper algorithm (there is no recursive call). How do you handle the common case of (> bx 0)? You'll need something like:
(define (mod a b)
(define (mod-iter ax bx)
(cond ((= bx 0) 0)
((< bx 0) (+ b bx))
((> bx 0) ...))) ;; <- something here with mod-iter?
(mod-iter a (- a b)))
First if you don't want to capture a variable name, use different variable names in the inner function. Second i think the arguments are wrong compared to the built-in version. (modulo 5 6) is 5 and (modulo 6 5) is 1. Anyways here is a variation in logrirthmic time. That based on generating a list of powers of b (2 4 8 16 32 ...) is b is 2, all the way up to just under the value of a. Then by opportunistically subtracting these reversed values. That way problems like (mod (expt 267 34) 85) return an answer very quickly. (a few hundred primitive function calls vs several million)
(define (mod a-in b-in)
(letrec ((a (abs a-in))
(sign (if (< 0 b-in) - +))
(b (abs b-in))
(powers-list-calc
(lambda (next-exponent)
(cond ((> b a) '())
((= next-exponent 0)
(error "Number 0 passed as the second argument to mod
is not in the correct range"))
(else (cons next-exponent (powers-list (* b next-exponent))))))))
(let ((powers-list (reverse (powers-list-calc b))))
(sign
(let loop ((a a) (powers-L powers-list))
(cond ((null? powers-L) a)
((> a (car powers-L))
(loop (- a (car powers-L)) powers-L))
(else (loop a (cdr powers-L)))))))))

Resources