【问题标题】:Possible to 'exit' racket prematurely可能过早“退出”球拍
【发布时间】:2021-06-16 23:37:24
【问题描述】:

为了使 C 函数短路(例如,出于测试目的),我可以将早期的 return 放在那里。例如:

int main(void) {
    puts("Hello");
    return;

    ...bunch of other code...
}

或者在 python 中做一个sys.exit(0)。有没有办法在 DrRacket / Scheme 中做到这一点?通常我会有一个包含几百行代码的工作簿,我只希望在退出之前运行前几个函数。例如:

#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...

这里有办法吗?

【问题讨论】:

    标签: scheme lisp racket


    【解决方案1】:

    #lang racket 可以使用名为...exit 的函数来做到这一点。试试:

    #lang racket
    
    (display 1)
    (exit 0)
    (display 2)
    

    #lang sicp 没有exit,但您可以从 Racket 中要求它:

    #lang sicp
    
    (#%require (only racket exit))
    
    (display 1)
    (exit 0)
    (display 2)
    

    函数的提前返回可以使用延续来完成。例如,使用let/cc 运算符:

    #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
    

    或者等效地,使用call-with-current-continuation,它同时存在于#lang racket#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))))))))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多