LISP |
|
(defun evensum ( l )
(if (null l) 0)
(if (evenp (car l)))
(+ (car l) evensum(cdr l)))
(evensum (cdr l))
)
(defun sumupto (a)
(if (equal '0 'a)
(+ '0 'a))
(+ 'a (sumupto (- 'a 1)))
)
3. Sum of squares of all the elements in the list
(defun squaresum (l)
(if (null l) ( )
(+ ( * (car l) (car l)) squaresum(cdr l))
)
4. Count the number of elements in a list
(defun noel (l)
(if (null l) 0)
(+ 1 (noel (cdr l)))
)
5. Sum all the elements upto n using iteration
(defun sumton (a)
(if (< n 0) nil)
(prog (sum)
(setq sum 0)
loop
(if (zerop a) (return sum))
(setq sum (+ sum a))
(setq a (-a 1))
(go loop)
)
)
6. To return the Nth element of the list
(defun nthel (n l)
(if (< n 0) nil)
(prog ( )
loop
(if (equal n 1) (return (car l)))
(setq n (- n 1))
(setq l (cdr l))
(go loop)
)
)
7. Write a LISP program addlist that takes as its arguments an element and a list.If the element is already in the list,the function returns the input list;otherwise it returns the list that includes the given element in the original list.
Example : (addlist 'c '(a,b,c,d)) = (a,b,c,d)
(addlist 'e '(a,b,c)) = (e,a,b,c)
(defun addlist(el lst)
(if (null lst) (return el))
(setq lst2 lst)
(prog ( )
start
(if (equal el(car lst2)) (return lst))
(setq lst2 (cdr lst))
(if (null lst2) (return (cons el lst)))
(go start)
)
)
8. Write a LISP program which reads five numbers,calculates their sum and the Nth power of individual numbers.The 2 results must be stored in 2 separate lists.
(defun sum&power( )
(setq n (read))
(setq n1 (read))
(setq n1p (power n n1))
(setq n2 (read))
(setq n2p (power n n2))
(setq n3 (read))
(setq n3p (power n n3))
(setq n4 (read))
(setq n4p (power n n4))
(setq n5 (read))
(setq n5p (power n n5))
(setq sum (+ n1 n2 n3 n4 n5))
)
(defun power (no val)
(setq count no)
(setq pow 1)
(prog ( )
start
(if ( <= count 0) (return pow))
(setq pow ( * val pow))
(setq count ( - count 1))
(go start)
)
)
(defun factorial (n)
(cond ((zerop n) 1)
(t ( * n (factorial ( - n 1))))
)
)
(defun factorial (n)
(do ((count n (- count 1))
(product n ( * product (- count 1))
((equal 0 count) product)
)
)
11. Write a LISP function max3 which finds maximum of 3 numbers.
(defun max3 (a b c)
(cond ((> a b) (cond ((> a c) a) (t c))
((> b c) b)
(t c)
)
)
12. Define the functions called left-rotate and right-rotate,these 2 functions takes a list and rotates the elements by one position as in
right-rotate '(a b c d) returns (d a b c)
left-rotate '(a b c d) returns(b c d a)
(defun right-rotate(lst)
(setq el(last lst))
(setq lst(reverse lst))
(setq lst(cdr lst))
(setq lst(reverse lst))
(setq lst(cons el lst))
)
(defun left-rotate(lst)
(setq el(car lst))
(setq lst(cdr lst))
(setq lst(list lst el))
)
LISP |
|
Ó CodeEverywhere