How to use call/cc for non-local exit in Scheme -
currently, studying scheme language. i'm confused in how use call-with-current-continuation.(call/cc) better understanding it, wrote example code non-local exits. doesn't work properly.
does know why? appreciated. in advance
[example code]
(define (product ls) (call/cc (lambda (return) (cond ((null? ls ) => (begin (display "list end") (newline) 1)) ;; ng ;;(return 1)) ;; ok ((not (number? (car ls))) => (begin (display "not number") (newline) (return 0))) (else => (begin (display (car ls)) (newline) (* (car ls) (product (cdr ls)))))))))
[repl output]
gosh> (product '(1 2 3)) ; works expected. ==> 1 ==> 2 ==> not number ==> 0 (return) gosh> (product '(1 2 3)) ;; doesn't work expected. expect 6 return value. ==> 1 ==> 2 ==> 3 ==> list end *** error: invalid application: (1 #t)
there couple of things going on here.
first , foremost, looks =>
you're inserting cond clauses causing problem. in scheme, =>
has special meaning... don't want. take them out, , think you'll see code behaves expect.
but: use of call/cc not causing non-local exit, believe you're intending. is, guess want 0 bypass of waiting multiplies, , it's not. see this, change 0 can't multiplied---say, string "not number"
--and watch fail.
this because you're re-binding return
on each call function. think want this:
(define (product ls) (call/cc (lambda (return) (letrec ([loop (lambda (ls) (cond ((null? ls ) (begin (display "list end") (newline) 1)) ;; ng ;;(return 1)) ;; ok ((not (number? (car ls))) (begin (display "not number") (newline) (return "not number"))) (else (begin (display (car ls)) (newline) (* (car ls) (loop (cdr ls)))))))]) (loop ls))))) (product '(1 2 3))
... produces output:
1 2 not number "not number" >
Comments
Post a Comment