scheme: resuming a loop after a condition has been signaled - conditional-statements

This program is using Scheme conditions and restarts to execute a procedure 10 times in a loop, and return the number of times the procedure did succeed.
Here the procedure throws an error each times n is a multiple of 3.
For some reason, the first error (n=3) is caught but the loop fails to resume with n=4:
(define (handle! thunk)
(bind-condition-handler
'() (lambda (condition)
(display "resuming...")
(invoke-restart (find-restart 'next)))
thunk))
(let loop((n 1) (count 0))
(display n)(display #\,)
(if (> n 10) count
(handle!
(call/cc
(lambda (cc)
(with-restart
'next "restart here"
(lambda ()
(cc (loop (1+ n) count)))
#f
(lambda ()
(if (= 0 (modulo n 3))
(error n "is multiple of 3!")
(loop (1+ n) (1+ count))))))))))
I failed to find examples of conditions and restarts beyond the ones at the MIT Scheme Reference.

The solution is to move down the call/cc to the loop argument 'count' which is affected by the condition:
(let loop((n 1) (count 0))
(display n)(display #\,)
(if (> n 10) count
(handle!
(lambda()
(loop (1+ n)
(call/cc
(lambda (cc)
(with-restart
'next "restart here"
(lambda ()
(cc count))
#f
(lambda ()
(if (= 0 (modulo n 3))
(error n "is multiple of 3!"))
(1+ count))))))))))
Runs correctly:
1 ]=> 1,2,3,resuming...4,5,6,resuming...7,8,9,resuming...10,11,
;Value: 7

Related

Iterating through a nested list using filter or fold Racket

I need to iterate through a list with sublists in Racket using list iteration and filtering, one of the lists is a nested list, I tried using "list?" and "car" to iterate inside but of course that would only apply to the first value of the sublist.
Is there a way to iterate through the whole nested list using list iteration and filtering?
(define (count-evens lst)
(length
(filter
(lambda (x)
(cond
[(and (list? x)
(and (number? (car x))
(eq? (modulo (car x) 2) 0)))
#t]
[(and (number? x)
(eq? (modulo x 2) 0))
#t]
[else
#f]))
lst)))
(count-evens '(1 2 5 4 (8 4 (b (10 3 3))) 3))
=> 3
Should return => 5
I would use a recursive function to do this but the assignment doesn't allow it.
"...assignment doesn't allow [recursive functions]"
Not sure what is allowed for this assignment, but
in ye olden days we processed recursive data structures with stacks...
(define (count-evens lst)
(define (lst-at stack) ;; (car stack) = index in deepest sub-list
;; produce list cursor within lst indexed by stack
(do ([stack (reverse stack) (cdr stack)]
[cursor (list lst) (list-tail (car cursor) (car stack))])
((null? stack) cursor)))
(do ([stack (list 0)
(cond
[(null? (lst-at stack))
(cdr stack)] ;; pop stack
[(pair? (car (lst-at stack)))
(cons 0 stack)] ;; push stack
[else ;; step through current (sub)list
(cons (+ 1 (car stack)) (cdr stack))])]
[count 0
(let ([item (car (lst-at stack))])
(if (and (number? item) (even? item)) (+ 1 count) count))])
((null? (lst-at stack)) count)))
> (count-evens '(1 2 5 4 (8 4 (b (10 3 3))) 3)) ;=>
5

Cond inside let doesn't work properly

I'm having a trouble with some Common Lisp code. I have two functions similars to the functions below:
(defun recursive-func (func lst num)
(let ((test
(some-func func
(first lst)
(first (rest lst))
num))
(next
(recursive-func func
(rest lst)
num)))
(cond ((null (rest lst)) nil)
((null test) next)
(t (cons test next)))))
(defun some-func (func a b num)
(if (> a b)
nil
(funcall func a b num)))
When the list has only one element I want recursive-func return nil, but it doesn't and calls some-func generating a evaluation abort because b is nil. Here is a trace of execution:
CL-USER> (recursive-func #'(lambda(x y z) (+ x y z)) '(1 2 3 4 5) 5)
0: (RECURSIVE-FUNC #<FUNCTION (LAMBDA (X Y Z)) {10035F6ABB}> (1 2 3 4 5) 5)
1: (SOME-FUNC #<FUNCTION (LAMBDA (X Y Z)) {10035F6ABB}> 1 2 5)
1: SOME-FUNC returned 8
1: (RECURSIVE-FUNC #<FUNCTION (LAMBDA (X Y Z)) {10035F6ABB}> (2 3 4 5) 5)
2: (SOME-FUNC #<FUNCTION (LAMBDA (X Y Z)) {10035F6ABB}> 2 3 5)
2: SOME-FUNC returned 10
2: (RECURSIVE-FUNC #<FUNCTION (LAMBDA (X Y Z)) {10035F6ABB}> (3 4 5) 5)
3: (SOME-FUNC #<FUNCTION (LAMBDA (X Y Z)) {10035F6ABB}> 3 4 5)
3: SOME-FUNC returned 12
3: (RECURSIVE-FUNC #<FUNCTION (LAMBDA (X Y Z)) {10035F6ABB}> (4 5) 5)
4: (SOME-FUNC #<FUNCTION (LAMBDA (X Y Z)) {10035F6ABB}> 4 5 5)
4: SOME-FUNC returned 14
4: (RECURSIVE-FUNC #<FUNCTION (LAMBDA (X Y Z)) {10035F6ABB}> (5) 5)
5: (SOME-FUNC #<FUNCTION (LAMBDA (X Y Z)) {10035F6ABB}> 5 NIL 5)
; Evaluation aborted on #<TYPE-ERROR expected-type: NUMBER datum: NIL>.
I hope someone would can help me, thanks.
The bindings in let are evaluated first, and only then you perform the tests in the cond.
You need only change a bit:
(defun recursive-func (func list num)
(if (null (rest list))
nil
(let ((test (some-func func
(first list)
(first (rest list))
num))
(next (recursive-func func
(rest list)
num)))
(cond ((null test) next)
(t (cons test next))))))
Note that the cond could also be written:
(if test (cons test next) next)
With your example:
(recursive-func (lambda (x y z) (+ x y z))
'(1 2 3 4 5)
5)
=> (8 10 12 14)
Alternatively, here is how you could decompose the task (in the REPL):
> (maplist (lambda (list)
(list
(first list)
(second list)))
'(1 2 3 4 5))
=> ((1 2) (2 3) (3 4) (4 5) (5 NIL))
Prefer SECOND instead of (first (rest ...)).
The last result is bound in the REPL to the variable *. Remove the last (useless) pair with BUTLAST:
(butlast *)
=> ((1 2) (2 3) (3 4) (4 5))
Then, for each couple in this list, call your function -- here it is just +. Notice the use of DESTRUCTURING-BIND:
(mapcar (lambda (list)
(destructuring-bind (a b) list
(+ a b 5)))
*)
=> (8 10 12 14)
So, basically, your function can be written as:
(defun map-pair-funcall (function list number)
(mapcar (lambda (pair)
(destructuring-bind (a b) pair
(funcall function a b number)))
(butlast (maplist (lambda (list)
(list (first list) (second list)))
list))))
And thus:
(map-pair-funcall #'+ '(1 2 3 4 5) 5)
=> (8 10 12 14)
Edit:
I missed the case where the supplied function might return NIL. Wrap the form calling mapcar by (remove NIL (mapcar ...)) to filter that out.
You can perform all that in one iteration by using MAPCON. The function iterates over sublists, and concatenates the resulting lists. The function being called should thus return list, and when you return NIL, the result are simply discarded.
Let's define ensure-list (or use the one from Alexandria):
(defun ensure-list (expr)
(if (listp expr) expr (list expr)))
The function wraps the returned value in a list, except if it is already a list (in particular, NIL). And then, the function is defined as follows:
(defun map-pair-funcall (function list number)
(mapcon (lambda (list)
(and (second list)
(ensure-list (funcall function
(first list)
(second list)
number))))
list))
You could also LOOP:
(defun map-pair-funcall (function list number)
(loop
for (a b) on list
for result = (and b (funcall function a b number))
when result
collect result))

Custom Scheme indexing function returns list-external value

I'm a newbie to scheme programming and I was writing small codes when I encountered the following issue and couldn't reason about it satisfactorily.
(define (at_i lst i)
(if (eq? i 0)
(car lst)
(at_i (cdr lst)
(- i 1) )))
Evaluation of (at_i '(1 2 3 4) 0) returns 1.
Now lets define same procedure with a lambda syntax.
(define (at_i lst i)
(lambda (vec x)
(if (eq? x 0)
(car vec)
(at_i (cdr vec)
(- x 1) )))
lst i)
But now Evaluation of (at_i '(1 2 3 4) 0) returns 0, which is not in the list and in general, it returns element at index-1.
I don't understand why this is happening.
Note: I just realized its not returning element at index - 1 but the index itself. The reason for this has been well explained below by #Renzo. Thanks!
First, you should indent properly the code if you intend to learn the language, since code indentation is very important to understand programs in Scheme and Lisp-like languages.
For instance, your function correctly indented is:
(define (at_i lst i)
(lambda (vec x)
(if (eq? x 0)
(car vec)
(at_i (cdr vec) (- x 1))))
lst
i)
From this you can see that you are defining the function at_i exactly as before in terms of a function with two parameters (lst and i), and whose body is constitued by three expressions: the first lambda (vec x) ... (- x 1)))), which is an (anonymous) function (lambda) which is not called or applied, the second, which is the first parameter lst, and finally the third which is the second parameter i. So, when the function at_i is called with two arguments, the result is the evaluation of the three expressions in sequence, the first two values are discarded (the function and the value of lst), and the result is the value of the second parameter i. This is reason for which the result of (at_i '(1 2 3 4) 0) is 0, since it is the value of i.
A proper redefinition of the function in lambda form would be the following, for instance:
(define at_i
(lambda (vec x)
(if (eq? x 0)
(car vec)
(at_i (cdr vec) (- x 1)))))
(at_i '(1 2 3 4) 0) ;; => 1
in which you can see that the name at_i, through the define, is associated to a two parameter function which calculates correctly the result.
eq? is memory object equality. Only some Scheme implementations interpret (eq? 5 5) as #t. Use = for numbers, eqv? for values, and equal? for collections.
(define (index i xs) ; `index` is a partial function,
(if (= i 0) ; `i` may go out of range
(car xs)
(index (- i 1) ; Tail recursion
(cdr xs) )))
Your second function returns the index because you missed parenthesis around the lambda's application. It should be
(define (index i xs)
((lambda (i' xs')
(if (= i' 0)
(car xs')
(index (- i' 1) ; Not tail-recursive
(cdr xs') )))
i xs))
But this is verbose and differs semantically from the first formulation.
You say you are defining the "same procedure with a lambda syntax", but you are not. That would be (define at_i (lambda lst i) ...). Instead, you are effectively saying (define (at_i lst i) 1 2 3), and that is 3, of course.
In your particular case, you defined the procedure at_i to return (lambda (vec x) ...), lst and i. Now, if you call (at_i '(1 2 3 4) 0), the procedure will return 0, since that is the value of i at this point.

extremely confused about how this "oop under-the-hood" example of a counter works

here's the make-counter procedure and calls to it
(define make-counter
(let ((glob 0))
(lambda ()
(let ((loc 0))
(lambda ()
(set! loc (+ loc 1))
(set! glob (+ glob 1))
(list loc glob))))))
> (define counter1 (make-counter))
counter1
> (define counter2 (make-counter))
counter2
> (counter1)
(1 1)
> (counter1)
(2 2)
> (counter2)
(1 3)
> (counter1)
(3 4)
i can't understand why does glob behaves as a class variable, while loc behaves as an instance variable.
It may be easiest to consider when each part of the code is run. You evaluate
(define make-counter (let ((0 glob)) ...))
just once, so the let is evaluated just once. That means that there's only one binding, and its value is shared by everything within the body of the let. Now, what's in body of the let? It's a lambda function, which becomes the value of make-counter:
(lambda () ; this function is the value of make-counter
(let ((loc 0)) ; so this stuff gets execute *each time* that
(lambda () ; make-counter is called
... ;
))) ;
Now, every time you call make-counter, you evaluate (let ((loc 0)) (lambda () …)), which creates a new binding and returns a lambda function that has access to it (as well as to the global binding from outside.
So each result from calling make-counter has access to the single binding of glob, as well as to access to a per-result binding of loc.
Let us examine the program:
(define make-counter
(let ((g 0))
(lambda ()
(let ((l 0))
(lambda ()
(set! l (+ l 1))
(set! g (+ g 1))
(list l g))))))
The program illustrates how an abstraction (lambda-expression) creates
a closure that contains references to the free variables.
It would be helpful to see and inspect the free variables explicitly,
so let's pretend we want to run the program above in a language
that doesn't support lambda. In other words, let try to rewrite
the program into one that uses simpler constructs.
The first is to get rid of assignments. Let's allocate a box
(think vector of length one) that can hold one value.
An assignment can then change the value that box holds using set-box!.
; Assignment conversion: Replace assignable variables with boxes.
; The variables l and g are both assigned to
(define make-counter
(let ((g (box 0)))
(lambda ()
(let ((l (box 0)))
(lambda ()
(set-box! l (+ (unbox l) 1))
(set-box! g (+ (unbox g) 1))
(list (unbox l) (unbox g)))))))
This program is equivalent to the original (try it!).
The next step is to annotate each lambda with its free variables:
(define make-counter
(let ((g (box 0)))
(lambda () ; g is free in lambda1
(let ((l (box 0)))
(lambda () ; g and l are free lambda2
(set-box! l (+ (unbox l) 1))
(set-box! g (+ (unbox g) 1))
(list (unbox l) (unbox g)))))))
Now we are ready to replace lambda with explicit closures.
A closure holds
i) a function with no free variables
ii) values of the free variable at the time the closure was created
We will use a vector to store i) and ii).
(define (make-closure code . free-variables)
(apply vector code free-variables))
We can get the function with no free variables like this:
(define (closure-code closure)
(vector-ref closure 0))
And we can the i'th free variable like this:
(define (closure-ref closure i)
(vector-ref closure (+ i 1)))
To apply a closure one calls the function with no free variables (code)
with both the closure (which code will need to find the values of the
free variables) and the actual arguments.
(define (apply-closure closure . args)
(apply (closure-code closure) closure args))
Here are the code corresponding to the lambda1
(define (lambda1 cl) ; cl = (vector lambda1 g)
(let ((g (closure-ref cl 0))) ; g is the first free variable of lambda1
(let ((l (box 0)))
(make-closure lambda2 g l))))
Since lambda1 was a function of no arguments, the only input is the closure.
The first thing it does is to retrieve the free value g.
Note that lambda1 returns a closure: (make-closure lambda2 g l)
Here we see that when the closure for lambda2 is made the values of g and l
are preserved.
Now lambda2:
(define (lambda2 cl) ; cl = (vector lambda2 g l)
(let ((g (closure-ref cl 0))
(l (closure-ref cl 1)))
(set-box! l (+ (unbox l) 1))
(set-box! g (+ (unbox g) 1))
(list (unbox l) (unbox g))))
Finally make-counter which simply makes a lambda1-closure:
(define make-counter (make-closure lambda1 (box 0)))
We are now ready to see our program in action:
(define counter1 (apply-closure make-counter))
counter1
(define counter2 (apply-closure make-counter))
counter2
(apply-closure counter1)
(apply-closure counter1)
(apply-closure counter2)
(apply-closure counter1)
The output is:
'#(#<procedure:lambda2> #&0 #&0)
'#(#<procedure:lambda2> #&0 #&0)
'(1 1)
'(2 2)
'(1 3)
'(3 4)
This means out program works in the same way as the original.
Now however we can examine the free variables of the two counters:
> counter1
'#(#<procedure:lambda2> #&4 #&3)
> counter2
'#(#<procedure:lambda2> #&4 #&1)
We can check that the two counters share the same g:
> (eq? (closure-ref counter1 0)
(closure-ref counter2 0))
#t
We can also check that they have two different boxes containing l.
> (eq? (closure-ref counter1 1)
(closure-ref counter2 1))
#f

Scheme Help - File Statistics

So I have to finish a project in Scheme and I'm pretty stuck. Basically, what the program does is open a file and output the statistics. Right now I am able to count the number of characters, but I also need to count the number of lines and words. I'm just trying to tackle this situation for now but eventually I also have to take in two files - the first being a text file, like a book. The second will be a list of words, I have to count how many times those words appear in the first file. Obviously I'll have to work with lists but I would love some help on where to being. Here is the code that I have so far (and works)
(define filestats
(lambda (srcf wordcount linecount charcount )
(if (eof-object? (peek-char srcf ) )
(begin
(close-port srcf)
(display linecount)
(display " ")
(display wordcount)
(display " ")
(display charcount)
(newline) ()
)
(begin
(read-char srcf)
(filestats srcf 0 0 (+ charcount 1))
)
)
)
)
(define filestatistics
(lambda (src)
(let ((file (open-input-file src)))
(filestats file 0 0 0)
)
)
)
How about 'tokenizing' the file into a list of lines, where a line is a list of words, and a word is a list of characters.
(define (tokenize file)
(with-input-from-file file
(lambda ()
(let reading ((lines '()) (words '()) (chars '()))
(let ((char (read-char)))
(if (eof-object? char)
(reverse lines)
(case char
((#\newline) (reading (cons (reverse (cons (reverse chars) words)) lines) '() '()))
((#\space) (reading lines (cons (reverse chars) words) '()))
(else (reading lines words (cons char chars))))))))))
once you've done this, the rest is trivial.
> (tokenize "foo.data")
(((#\a #\b #\c) (#\d #\e #\f))
((#\1 #\2 #\3) (#\x #\y #\z)))
The word count algorithm using Scheme has been explained before in Stack Overflow, for example in here (scroll up to the top of the page to see an equivalent program in C):
(define (word-count input-port)
(let loop ((c (read-char input-port))
(nl 0)
(nw 0)
(nc 0)
(state 'out))
(cond ((eof-object? c)
(printf "nl: ~s, nw: ~s, nc: ~s\n" nl nw nc))
((char=? c #\newline)
(loop (read-char input-port) (add1 nl) nw (add1 nc) 'out))
((char-whitespace? c)
(loop (read-char input-port) nl nw (add1 nc) 'out))
((eq? state 'out)
(loop (read-char input-port) nl (add1 nw) (add1 nc) 'in))
(else
(loop (read-char input-port) nl nw (add1 nc) state)))))
The procedure receives an input port as a parameter, so it's possible to apply it to, say, a file. Notice that for counting words and lines you'll need to test if the current char is either a new line character or a white space character. And an extra flag (called state in the code) is needed for keeping track of the start/end of a new word.