Reputation: 110380
To short-circuit a C function (for example, for testing purposes), I can put an early return
in there. For example:
int main(void) {
puts("Hello");
return;
...bunch of other code...
}
Or do a sys.exit(0)
in python. Is there a way to do this in DrRacket / Scheme? As often I will have a workbook with a few hundred lines of code and I only want the top few functions to run before exiting. For example:
#lang sicp
(define (filtr function sequence)
(if (null? sequence) nil
(let ((this (car sequence))
(rest (cdr sequence)))
(if (function this) (cons this (filtr function rest))
(filtr function rest)))))
(filtr (lambda (x) (> x 5)) '(1 2 3 4 5 6 7 8 9))
(exit) ; ?? something like this I can drop in to terminate execution?
...200 more lines of code...
Is there a way to do that here?
Upvotes: 0
Views: 484
Reputation: 6502
#lang racket
can do that with the function named... exit
. Try:
#lang racket
(display 1)
(exit 0)
(display 2)
#lang sicp
doesn't have exit
, but you can require it from Racket:
#lang sicp
(#%require (only racket exit))
(display 1)
(exit 0)
(display 2)
Early return from a function can be done using continuation. For example, with the let/cc
operator:
#lang racket
(define (fact x)
(let/cc return
(if (= x 0)
1
(begin
(display 123)
(return -1)
(display 456)
(* x (fact (- x 1)))))))
(fact 10)
;; display 123
;; and return -1
Or equivalently, with call-with-current-continuation
, which exists in both #lang racket
and #lang sicp
:
(define (fact x)
(call-with-current-continuation
(lambda (return)
(if (= x 0)
1
(begin
(display 123)
(return -1)
(display 456)
(* x (fact (- x 1))))))))
Upvotes: 2