lisp中的cond函数解读

 cond

The version of triangle-recursively described earlier is written with the if special form. It can also be written using another special form called cond. The name of the special form cond is an abbreviation of the word ‘conditional’.

Although the cond special form is not used as often in the Emacs Lisp sources as if, it is used often enough to justify explaining it.

The template for a cond expression looks like this:

     (cond
      body...)

where the body is a series of lists.

Written out more fully, the template looks like this:

     (cond
      (first-true-or-false-test first-consequent)
      (second-true-or-false-test second-consequent)
      (third-true-or-false-test third-consequent)
       ...)

When the Lisp interpreter evaluates the cond expression, it evaluates the first element (the car or true-or-false-test) of the first expression in a series of expressions within the body of the cond.

If the true-or-false-test returns nil the rest of that expression, the consequent, is skipped and the true-or-false-test of the next expression is evaluated. When an expression is found whose true-or-false-test returns a value that is not nil, the consequent of that expression is evaluated. The consequent can be one or more expressions. If the consequent consists of more than one expression, the expressions are evaluated in sequence and the value of the last one is returned. If the expression does not have a consequent, the value of the true-or-false-test is returned.

If none of the true-or-false-tests test true, the cond expression returns nil.

Written using cond, the triangle function looks like this:

     (defun triangle-using-cond (number)
       (cond ((<= number 0) 0)
             ((= number 1) 1)
             ((> number 1)
              (+ number (triangle-using-cond (1- number))))))

In this example, the cond returns 0 if the number is less than or equal to 0, it returns 1 if the number is 1 and it evaluates (+ number (triangle-using-cond (1- number))) if the number is greater than 1.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值