循環:java
1)do循環
python
語法:(do ((變量名 變量初值 (變量變化語句))) 函數
(結束條件 返回值) spa
循環主體)
rest
CL-USER> (defun draw-line (x) (do ((i 0 (1+ i))) ((>= i x) nil) ;;nil能夠忽略 (format t "*"))) CL-USER> (draw-line 3) *** NIL CL-USER> (draw-line 10) ********** NIL CL-USER> (defun draw-box (r l) (do ((i 0 (1+ i))) ((>= i r) nil) ;;nil能夠忽略 (draw-line l) (format t "~%"))) CL-USER> (draw-box 4 10) ********** ********** ********** ********** NIL
遞歸:
code
1)斐波那契數列orm
求第n個斐波那契數
遞歸
(defun fib (n) (cond ((equal n 1) 1) ((equal n 2) 1) (t (+ (fib (- n 1)) (fib (- n 2)))))) 改進版: (defun fib (n) (if (or (= n 1) (= n 2)) 1 (+ (fib (- n 1)) (fib (- n 2)))))
打印斐波那契數列form
(defun print-fib (n) (do ((i 0 (1+ i))) ((>= i n)) (format t "~A~%" (fib i))))
2)另外一種沒有循環體的求斐波那契數列class
(defun fib2 (x) (do ((n 0 (1+ n)) (cur 0 next) (next 1 (+ cur next))) ((= x n) cur)))
3)階乘
CL-USER> (defun factorial (n) (if (= n 1) 1 (* n (factorial (- n 1))))) FACTORIAL CL-USER> (factorial 10) 3628800 CL-USER> (factorial 5) 120
5)能夠用trace函數查看遞歸運行內部情形
CL-USER> (defun count-slices (loaf) (cond ((null loaf) 0) (t (1+ (count-slices (rest loaf)))))) CL-USER> (count-slices '(x)) 1 CL-USER> (count-slices '(a e i o u)) 5 CL-USER> (trace count-slices) (COUNT-SLICES) CL-USER> (count-slices '(a e i o u)) 0: (COUNT-SLICES (A E I O U)) 1: (COUNT-SLICES (E I O U)) 2: (COUNT-SLICES (I O U)) 3: (COUNT-SLICES (O U)) 4: (COUNT-SLICES (U)) 5: (COUNT-SLICES NIL) 5: COUNT-SLICES returned 0 4: COUNT-SLICES returned 1 3: COUNT-SLICES returned 2 2: COUNT-SLICES returned 3 1: COUNT-SLICES returned 4 0: COUNT-SLICES returned 5 5
(未完待補充。。。)