-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.rkt
112 lines (86 loc) · 2.36 KB
/
demo.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#lang racket/base
(require racket)
;; CALL/CC
;; Short demo on continuations and call/cc
;; continuations
;; stuff left to compute. run-time concept.
;; CPS js example
;; Few examples are taken from the following sources:
;;
;; - http://matt.might.net/articles/programming-with-continuations--exceptions-backtracking-search-threads-generators-coroutines/
;; - https://beautifulracket.com/explainer/continuations.html
(+ 1 (* 2 3))
;; 2 * 3 = r
;; r + 1
(let ((cont #f))
(call/cc (lambda (k) (set! cont k)))
cont)
(display "abhinav tushar is sleepy")
(display
(call/cc (lambda (cc)
(display "I got here.\n")
(cc "This string was passed to the continuation.\n")
(display "But not here.\n"))))
(+ 1 (call/cc (lambda (k) k 1)))
;;; JUMPS
;; 0 -> 9
;; while True:
;; if n == 1:
;; print(done)
;; break
;; else:
;; print("hello")
(let ((cont #f))
(call/cc (lambda (k) (set! cont k)))
(if (= (random 10) 1)
(begin
(display "done")
(set! cont void))
(display "hello\n"))
(cont "manchanda"))
;;; RETURN
(define (find-multiple factor)
(call/cc (lambda (return)
(for ([num (shuffle (range 200))])
(when (zero? (modulo num factor))
(return num))))))
(find-multiple 43)
;;; EXCEPTIONS
; current-continuation : -> continuation
(define (current-continuation)
(call-with-current-continuation
(lambda (cc)
(cc cc))))
; exception-stack : list[continuation]
(define exception-stack '())
; (try exp ... catch catch-procedure) runs
; exp ..., and invokes catch-procedure with
; the value passed to throw.
(define-syntax try
(syntax-rules (catch)
((_ exp ... catch proc)
; =>
(let ((cc (current-continuation)))
(cond
((procedure? cc)
(dynamic-wind
(lambda ()
(set! exception-stack (cons cc exception-stack)))
(lambda ()
exp ...)
(lambda ()
(set! exception-stack (cdr exception-stack)))))
((pair? cc)
(proc (cadr cc))))))))
(define (throw exception-value)
(let ((handler (car exception-stack)))
(handler (list 'exception exception-value))))
; Example:
(try (begin
(display "stuff")
(throw 'foo))
catch
(lambda (exn)
(display "got inner exception: ")
(display exn)
(newline)))