首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使lambda中的函数在lambda主体内使用的另一个函数中调用

如何使lambda中的函数在lambda主体内使用的另一个函数中调用
EN

Stack Overflow用户
提问于 2018-07-23 12:51:34
回答 2查看 79关注 0票数 1

我想使用call/cc来模拟异常处理语句:try...(抛出)...exception。代码如下:

代码语言:javascript
复制
(define (month n) ; check if it's a month number (1-12)
  (if (or (not (integer? n)) (< n 1) (> n 12))
    (throw -1)
    (display n)
  )
)

(define error (call/cc
   (lambda(throw)
     (begin
       (month 12)
       (month -1)
       (throw -1) ; won't be executed
       (month 10)
       (display "Hello world")
      )
     )
   )
 )

(if error
  (display Error occured!")
)

但是,当我执行它时,它显示了错误(在biwascheme中):

代码语言:javascript
复制
Error: execute: unbound symbol: "throw" [(anon), month]

我认为lambda中的抛出与被调用的函数"month“中的抛出不同,但是,我该如何解决呢?用一些关键字做marco可以解决这个问题吗?例如:

代码语言:javascript
复制
(define-syntax exception-handling
    (syntax-rules (throw raise error)
      ((_ body catch)
        (define (error
                  (call/cc (lambda (throw) (begin body))))
        )
        (if error (begin catch)))
    )
 )
EN

回答 2

Stack Overflow用户

发布于 2018-07-24 01:09:47

下面是一个如何使用call-with-current-continuation进行“抛出”的示例。

代码语言:javascript
复制
#lang r5rs

(define (month n) ; check if it's a month number (1-12)
  (call-with-current-continuation
    (lambda (throw)       
      (define ok (and (integer? n) (<= 1 n 12)))
      (if (not ok)
        (throw "the month number must be between 1 and 12"))
      (display n)
      (newline))))

(month 12)
(month -1)
(month 10)
(display "Hello world\n")
票数 1
EN

Stack Overflow用户

发布于 2018-07-25 04:24:42

我已经找到了模拟try和异常处理的方法:

代码语言:javascript
复制
(define-syntax try
   (syntax-rules (catch)
     ((_ body catch handling)
        (let ()
          ; evaluating body and save it as an exception.
          (define except (begin body)) 
          (if (and
                (pair? except)
                (eq? (car except) 'exception))
             (handling except)
          )
        )
      )
   )
)

; returns an exception '(exception, "Error messenge")
(define (exception-content msg throw)
  (throw (cons 'exception msg)))
; throw an exception if n = 0
(define (reciprocal n throw)
  (if (= n 0)
     (exception-content "Div 0 error" throw)
     (/ 1 n)
  )
)

; f1(n) = reciprocal(n) + 1
(define (f1 n throw)
  (+ (reciprocal n throw) 1)
)

; main program 
(try ; with call/cc and the continuation variable "throw"
   (call-with-current-continuation
     (lambda (throw)
       (display (f1 2 throw))
       (newline)
       (display (f1 0 throw))

       ; the following won't be executed
       (newline)
       (display (f1 1 throw))
     )
   )

 catch
   ; exception handling
   (lambda (exception)
     (display (cdr exception))
   )
)

打印结果为:

代码语言:javascript
复制
3/2
Div 0 error
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51471725

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档