边读 Emacs Lisp Intro 边做题(三)

<2022-09-01 Thu>

边读Emacs Lisp Intro边做题(三)

打开emacs,按C-h i打开Info页,找到Emacs Lisp Intro

硬着头皮把11.4的习题做了,对emacs-lisp写递归和使用cond函数稍微有了点感觉,但是我写的代码感觉好像都差不多呢!

前两个函数是11.4.111.4.2while循环写法,紧接着的两个函数对它们的递归写法,最后两个是对它们的cond写法。

(defun exercise-11.4-1 (numbers-of-rows)
  "Write a function similar to ‘triangle’ in which each row has a
value which is the square of the row number.  Use a ‘while’ loop."
  (let ((total 0)
        (row-number 1))
    (while (<= row-number numbers-of-rows)
      (setq total (+ total (* row-number row-number)))
      (setq row-number (1+ row-number)))
    total))

(defun exercise-11.4-2 (numbers-of-rows)
  "Write a function similar to ‘triangle’ that multiplies instead of adds the values."
  (let ((total 1)
        (row-number 1))
    (while (<= row-number numbers-of-rows)
      (setq total (* total row-number))
      (setq row-number (1+ row-number)))
    total))
(defun exercise-11.4-1-recursively (numbers-of-rows)
  "Write a function similar to ‘triangle’ in which each row has a
value which is the square of the row number."
  (if (= numbers-of-rows 1)
      1
    (+
     (* numbers-of-rows numbers-of-rows)
     (exercise-11.4-1-recursively (1- numbers-of-rows)))))

(defun exercise-11.4-2-recursively (numbers-of-rows)
  "Write a function similar to ‘triangle’ that multiplies instead of adds the values."
  (if (= numbers-of-rows 1)
      1
    (* numbers-of-rows (exercise-11.4-2-recursively (1- numbers-of-rows)))))
(defun exercise-11.4-1-cond (numbers-of-rows)
  "Write a function similar to ‘triangle’ in which each row has a
value which is the square of the row number."
  (cond
   ((= numbers-of-rows 1) 1)
   ((> numbers-of-rows 1)
    (+ (* numbers-of-rows numbers-of-rows)
       (exercise-11.4-1-cond (1- numbers-of-rows))))))

(defun exercise-11.4-2-cond (numbers-of-rows)
  "Write a function similar to ‘triangle’ that multiplies instead of adds the values."
  (cond
   ((= numbers-of-rows 1) 1)
   ((> numbers-of-rows 1)
    (* numbers-of-rows (exercise-11.4-2-cond (1- numbers-of-rows))))))
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值