用于/继续进行方案/lisp [英] for/continue in scheme/lisp

查看:58
本文介绍了用于/继续进行方案/lisp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Scheme(R5RS)为类C语言编写一个小型解释程序,并尝试转换如下内容:

I'm writing a small interpreter for a C-like language in Scheme (R5RS) and trying to convert something like:

for (i = 0; i < 100; i++)
{
    if (isprime(i)) continue;
    else /* do something with i */
}

有效的Scheme(isprime函数只是一个示例,并不重要).

to valid Scheme (the isprime function is just an example and not important).

但是,经过一段时间的尝试,我仍然无法找到一种有效/简单的方法来将Schemes的等效条件添加到Scheme中的do循环中.更好的是使用"for"宏,该宏允许使用"continue"和"break".

However, after trying for some time, I have not been able to find an efficient/simple way to add the equivalent of a continue statement to a do loop in Scheme. What would be even better would be a "for" macro which allows "continue" and "break" to be used.

我正在考虑切换到Common Lisp.这样的事情在CL中会更容易吗?

I'm considering switching to Common Lisp. Would this sort of thing be any easier in CL?

推荐答案

我们可以将FOR编写为宏.通用Lisp版本:

We can write FOR as a macro. The Common Lisp version:

(defmacro for ((var start end) &body body)
  (let ((block-name (gensym "BLOCK")))
    `(loop for ,var from ,start below ,end
           do (block ,block-name
                (flet ((continue ()
                         (return-from ,block-name)))
                  ,@body)))))


CL-USER 2 > (for (i 10 20)
              (if (evenp i) (continue))
              (print i))

11 
13 
15 
17 
19 

这篇关于用于/继续进行方案/lisp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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