<2022-09-01 Thu>
边读Emacs Lisp Intro
边做题(三)
打开emacs
,按C-h i
打开Info
页,找到Emacs Lisp Intro
。
硬着头皮把11.4
的习题做了,对emacs-lisp
写递归和使用cond
函数稍微有了点感觉,但是我写的代码感觉好像都差不多呢!
前两个函数是11.4.1
和11.4.2
的while
循环写法,紧接着的两个函数对它们的递归写法,最后两个是对它们的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))))))