Lisp Programs
Lisp Programs
(defun sum-square (x y)
(+ (* x x) (* y y))
)
2. Define a LISP function to compute difference of square. (If x>y
return x2-y2 otherwise return y2-x2)
(defun diff-square (x y)
(cond ((> x y) (- (* x x) (* y y)))
(t (- (* y y) (* x x)))
)
)
3. Define a recursive LISP function to solve Ackermanns functions.
Ackermanns function:
n+1 if m=0
A(m, n)= A(m-1, 1) if n=0
A(m-1, A(n-1)) Otherwise
(defun Ackermann(m n)
(cond ((zerop m) (+ n 1))
((zerop n) (Ackermann (- m 1) 1))
(t (Ackermann (- m 1) (Ackermann m (- n 1))))
)
)
4. Define a recursive LISP function to compute factorial of given
number.
(defun fact (n)
(cond ((or (= n 0) (= n 1) 1)
(t (* n (fact (- n 1))))
)
)
5. Define a recursive LISP function which takes one argument as a list and return last
element of the list. (Do not use last primitive)
(defun lastl (l)
(cond ((null l) nil)
((null (cdr l)) (car l))
(t (lastl (cdr l)))
)
)
6. Define a recursive LISP function which takes one argument as a list and return list except
last element of the list. (Do not use butlast primitive)
(defun mybutlast (lst)
(cond ((endp (cdr lst)) nil)
(t (cons (car lst) (mybutlast (cdr lst))))
)
)
7. Define a recursive LISP function which takes one argument as a list and return reverse of
the list. (Do not use reverse primitive)
(defun myreverse (lst)
(cond ((null lst) nil)
(t (append (myreverse (cdr lst)) (list (car lst))))
)
)
8. Define a recursive LISP function which takes two arguments first an atom
and second a list. Returns a list after removing first occurrence of
that atom within the list.
(defun remove (lst x)
(cond ((null lst) nil)
((equal (car lst) x) (cdr lst))
(t (cons (car lst) (remove (cdr lst) x)))
)
)
9. Define a Recursive LISP function which appends two lists together.
(defun list-append (L1 L2)
(if (null L1) L2
(cons (car L1) (list-append (cdr L1) L2))
)
)
10. Define a recursive LISP function which takes 2 lists as arguments and
returns a list containing alternate elements from each list.
(defun alt (x y)
(cond ((and (endp x) (endp y)) nil)
((endp x) y)
((endp y) x)
(t (cons (car x) (alt y (cdr x))))
)
)
11.Write a recursive function in LISP to print summation of all integers from a
list of integers.
(defun sum-lst (lst)
(cond ((null lst) 0)
(t (+ (car lst) (sum-lst (cdr lst))))
)
)
12. Define a LISP function newlist that takes one
argument, and returns it as a list. If the argument is
already a list, the function returns the list unaltered. If
the argument is an atom, it as a list.
(defun newlist (element)
(cond ((listp element) element)
(t (cons element nil))
)
)
(a b c) (b c d)
(cond ((= a b) a)
1. Write a LISP function that reads two lists and check whether
they are equal or not.
(defun compare (lst1 lst2)
((eq (car lst1) (car lst2)) (compare (cdr lst1) (cdr lst2)))
(t nil)
(cond ((= n 0) 0)