在方案中定义语法问题 [英] define-syntax issue in scheme

查看:152
本文介绍了在方案中定义语法问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在想如何在计划中定义我的for循环出了什么问题。
每当我尝试运行一个for语句,它会运行一段时间,然后崩溃。

$ $ p $ (define-语法规则(:)
[(_(initial:test:update)body)
(begin
(if test
(begin body更新
(for [test:update] body))))]
[(_(test:update)body)
(if test
(begin body update
(for [test:update] body)))]))

它应该运行初始条件,检查测试,运行正文,然后循环到下一次运行。

解决方案

您的宏失败,因为宏是递归的,没有基本的情况。因此,在编译期间,宏扩展,再次扩展,再次扩展,永远。



这是一个实现:


(语法规则():
((_(initial:test:update)body)
(begin ($($())
(让重复()
(当测试
body
更新
(重复)))))
body)
(for(#f:test:update)body))))


> (let((foo 0))
(for((set!foo 5):(positive?foo):( set!foo( - foo 1)));; w / init
(显示YES(换行))))
YES
YES
YES
YES
YES
> (((foo 2))
(for((positive?foo)):(set!foo( - foo 1)));; w / o init
(begin('YES')(换行符)))



I'm wondering what is going wrong with how I'm defining my for-loop in scheme. Whenever I try running a for statement with it it runs for quite a while and then crashes.

(define-syntax for 
  (syntax-rules (:)
    [(_ (initial : test : update) body) 
     (begin initial 
            (if test 
                (begin body update 
                       (for [test : update] body))))]
    [(_ (test : update) body) 
     (if test 
         (begin body update 
                (for [test : update] body)))]))

It should run the initial condition, check the test, run the body, and then loop to the next run.

解决方案

Your macro fails because the macro is recursive and there is no base case. Thus during compilation, the macro expands, and expands again, and expands again, forever.

Here is an implementation:

(define-syntax for
  (syntax-rules (:)
    ((_ (initial : test : update) body)
     (begin initial
            (let repeating ()
              (when test 
                body
                update
                (repeating)))))
    ((_ (test : update) body)
     (for (#f : test : update) body))))


> (let ((foo 0)) 
    (for ((set! foo 5) : (positive? foo) : (set! foo (- foo 1))) ;; w/ init
      (begin (display 'YES) (newline))))
YES
YES
YES
YES
YES
> (let ((foo 2)) 
    (for ((positive? foo) : (set! foo (- foo 1)))  ;; w/o init
      (begin (display 'YES) (newline)))
YES
YES

这篇关于在方案中定义语法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆