Sei sulla pagina 1di 2

;;; Recursive function

;;;
;;; http://www.cs.sfu.ca/CourseCentral/310/pwfong/Lisp/1/tutorial1.html
(defun pow(b e)
;; power. b**e
(if (= e 1)
b
(* b (pow b (- e 1)))))
(defun tri(n)
;; triangular numbers.
(if (= n 1)
1
(+ n (tri (- n 1)))))
(defun fact(n)
;; factorial
(if (= n 1)
1
(* n (fact (- n 1)))))
(defun bin(n r)
;; binomial k.
(if (or (zerop r) (> r (+ n 1)))
1
(+ (bin (- n 1) (- r 1)) (bin (- n 1) r))))
(defun rec-list-length(L)
;; recursive length of list
(if (null L)
0
(+ 1 (rec-list-length (rest l)))))
(defun list-sum(L)
;; recursive sum of list
(if (null L)
0
(+ (first L) (list-sum (rest L)))))
(defun idx(n L)
;; return L[n]
(if (null L)
nil
(if (zerop n)
(first L)
(idx (- n 1) (rest L)))))
(defun last-one(L)
;; return L[-1] non-nil
(idx (1- (rec-list-length L)) L))
(defun is-in(k L)
;; check if k in L
(if (null L)
nil
(if (equal k (first L))
t
(is-in k (rest L)))))

(defun appendi(L1 L2)


;; append L2 to L1
(if (null L1)
L2
(cons (first L1) (appendi (rest L1) L2))))
(defun but-last(L)
;; returns L without last elements
(if (= (rec-list-length L) 1)
nil
(cons (first L) (but-last (rest L)))))
(defun counter(k L)
;; counts occourrences of k in L
(cond
((null L) 0)
((equal (first L) k)
(1+ (counter k (rest L))))
(t (counter k (rest L)))))
(defun list-inters(L1 L2)
;; intersection between L1 L2
(cond
((or (null L1) (null L2))
nil)
((is-in (first L1) L2)
(cons (first L1) (list-inters (rest L1) L2)))
(t
(list-inters (rest L1) L2)) ))
(defun list-union (L1 L2)
;; act as the built-in *union*
(cond
((null L1) L2)
((not (is-in (first L1) L2)) ;if L1[n] not in L2
(cons (first L1) (list-union (rest L1) L2))) ;append L1[n] to *recursion*
(t (list-union (rest L1) L2))))
(defun list-difference (L1 L2)
;; difference L1-L2 in sets
(cond
((null L1) nil)
((not(is-in (first L1) L2))
(cons (first L1) (list-difference (rest L1) L2)))
(t (list-difference (rest L1) L2)) ))

Potrebbero piacerti anche