ELisp编程九:循环

最简单的形式

(while TRUE-OR-FALSE-TEST
  BODY...)

比如:

(setq x 10
      total 0)
(while (plusp x)  ; while x is positive
  (incf total x)  ; add x to total
  (decf x))       ; subtract 1 from x

初始设置x=10,total=0

如果x>=0则继续,否则退出循环

每次循环都将当前的x的值加到total上,然后让x=x-1

执行了10次循环后,最后x的值为-1.


下面的这个例子的代码演示了如何遍历list中的每个元素,并打印:

(setq animals '(gazelle giraffe lion tiger))
(defun print-elements-of-list (list)
       "Print each element of LIST on a line of its own."
       (while list
         (print (car list))
         (setq list (cdr list))))
(print-elements-of-list animals)

car函数返回list中的第一个元素

cdr函数将list中第二个元素开始的元素作为一个新的list返回


break中断循环

如果我们要实现常见的break跳出循环,比如像下面的JavaScript代码:

var x = total = 0;
while (true) {
  total += x;
  if (x++ > 10) {
    break;
  }
}

ELisp中应该这样写:

(setq x 0 total 0)
(catch 'break
  (while t
    (incf total x)
    (if (> (incf x) 10)
        (throw 'break total))))

catch函数获取到里面throw函数返回的total,当然也可不必返回有效值,用nil即可。

(throw 'break nil)


continue跳过后面代码,进入下一个循环

或用catch ‘break,还可以实现continue

(setq x 0 total 0)
(while (< x 100)
  (catch 'continue
    (incf x)
    (if (zerop (% x 5))
        (throw 'continue nil))
    (incf total x)))



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值