scheme - Change a function into CPS, to not use call/cc -


i understand how implement coroutines without call/cc.

i began little example understand how modify code can use without call/cc:

(define x 0)  ( + 2 (call-with-current-continuation   (lambda (cont)     (set! x cont)   3)))  (x 4) 

when execute function call/cc gives me 5, 6 when execute (x 4).

i use function replace call/cc :

(define (call/cc-cps f continuation)    (f continuation continuation)) 

i tried change function cps (continuation-passing style):

(call/cc-cps   (lambda (exit cont)    (set! x cont)    3) (lambda (value)   (+ value 2))) 

but when execute it, instead of having 5 3. 6 (x 4).

can tell me wrong ? thank

with cps don't have top level continuations prompts comparison need put code in empty let this:

(let ()   (define x 0)   (+ 2 (call-with-current-continuation          (lambda (cont)            (set! x cont)            3))) ; ==> 5   (x 4))   ; ==> 6   ; ==> 6   ; ==> 6   ; ... forever  

this becomes infinite loop since call (x 4) after summing every time.

;; cps-version of + (define (+& b continuation)   (continuation (+ b))) 

notice &. it's used indicate function takes 1 argument, continuation. in cps define call/cc this:

(define (call/cc& f& continuation)   (define (exit& value actual-continuation)     (continuation value))   (f& exit& continuation)) 

notice it's quite different version. passes exit function f& , instead of using passed actual-continuation remaining computation passes continuation of call/cc& instead.

now can rewrite program this:

((lambda (x& halt-continuation)    (call/cc& (lambda (cont continuation)               ((lambda (ingnored-undefined-value) (continuation 3))                (set! x& cont)))             (lambda (three)               (+& 2 3 (lambda (ignored-result)                       (x& 4 halt-continuation))))))  0 values) 

ignored-result 5 first time , infinite other times calculates 4 ignored-result 6, in non cps version let.

i use drracket has pretty darn debugger , can step , see happening. added break point @ +& call , pressed |> , saw variable three fist 3 4 infinite times.

cps isn't easy. call/cc gives benefits of cps without making code harder read. implementing coroutines without call/cc challenging me write though quite complex call/cc begin with, since have infinite loop if not careful.


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -