CS152
Chris Pollett
Oct 27, 2021
function search(key : string) : string; var rtn : string; ... (* nested procedure definition *) procedure search_file(fname : string); ... begin ... for ... (* iterate over lines *) ... if found(key, line) then begin rtn := line; goto 100; end; ... end; ... begin (* search *) for ... (* iterate over files *) ... search_file(fname); ... 100: return rtn; end;
def searchFile(fname, pattern) file = File.open(fname) file.each {|line| throw :found, line if line =~ /#{pattern}/ } end match = catch :found do searchFile("f1", key) searchFile("f2", key) searchFile("f3", key) "not found\n" #default value for catch, end #if control gets this far print match
(define the-continuation #f) (define (test) (let ((i 0)) (call/cc (lambda (env) (set! the-continuation env))) (set! i (+ i 1)) i)) > (test) 1 > (the-continuation) 2 > (the-continuation) 3
if a == b then ... elsif a == c then ... elsif a == d then ... else ... end
(cond ((= A B) (...)) ; what to do if A==B ((= A C) (...)) ; what to do if A==C ((= A D) ; what to do if A==D (...)) (T ; what to do in all other cases (...)) )
if ((A > B) and (C > D)) or (E /= F) then then_clause else else_clausemight be implemented as (without shortcut evaluation):
r1 := A r2 := B r1 := r1 > r2 r2 := C r3 := D r2 := r2 > r3 r1 := r1 & r2 r2 := E r3 := F r2 := r2 /= r3 r1 := r1 | r2 if r1 = 0 goto L2 L1:then_clause goto L3 L2:else_clause ... L3:
r1 := A r2 := B if r1 <= r2 goto L4 r1 := C r2 := D if r1 > r2 goto L1 L4:r1:=E r2 := F if r1 = r2 goto L2 L1:then_clause ... goto L3 L2:else_clause ... L3:
switch (my_expr) { case 1: //some code; break; case 2: case 7: //some code break; case 3: case 4: case 5: //some code break; default: // some code }could be implemented as:
T: &L1 -- controlling expression = 1 &L2 &L3 &L3 &L3 &L5 &L2 &L5 &L5 &L4 -- controlling expression = 10 L6:r1:=... -- calculate controlling expression if r1 < 1 goto L5 -- L5 is the default case arm if r1 > 10 goto L5 -- subtract off lower bound r1 -:= 1 r1 := T[r1] goto *r1 L7:
do i = 1, 10, 2 ... enddo
for (i = 1; i <= 10; i +=2) { ... }
r1 := first r2 := step r3 := last goto L2 L1: ... -- loop body r1 := r1 + r2 L2: if r1 ≤ r3 goto L1