作者yauhh (哟)
看板Programming
标题Re: [请益] 没有想像中简单的小问题
时间Tue Mar 24 10:08:01 2009
※ 引述《yauhh (哟)》之铭言:
: ANSI Common-Lisp 版本:
再修改一下自己的程式. 在贴程式之前,先谈这一题,看了前面一连串的程式码,
觉得其中在思考构面和程式的规格大不大,有相当微妙的优缺点.
像原po的程式,就是写多少程式做多少事情; 先印上半段,再印下半段.
但通常解决这种问题,我们比较希望抓住关键的参数,然後能决定输出多大的菱形.
我将自己的Lisp程式改一下,觉得比较好:
要输入 (main 3 5), 3 是上尖端数字, 5 是菱形高度. 於是它要印出尖端是 3,
高度是 5 的菱形. 所以程式如下:
(defun main (n h)
(diamond (list (repeat-char #\space (/ (- h 1) 2)) n)))
(defun diamond (struct)
(cond ((null (car struct)) (print* (reverse (cdr struct))) (terpri))
(t (print* struct) (terpri)
(setf ta (car struct))
(setf td (cdr struct))
(pop ta)
(setf tx (pop td))
(push tx td)
(push (+ tx 1) td) (push (+ tx 2) td)
(diamond (cons ta td))
(print* struct) (terpri))))
(defun print* (list)
(cond ((null (car list)) nil)
((listp (car list)) (print* (car list)) (print* (reverse (cdr list))))
(t (princ (car list)) (print* (cdr list)))))
(defun repeat-char (c n)
(cond ((< n 1) nil)
(t (cons c (repeat-char c (- n 1))))))
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 59.112.224.82