# Sample of LISP code

## Recommended Posts

In my recent class, we did a series of languages from different paradigms to get an understanding of how they are used, pros/cons, etc. Here is some code I wanted to share from a portion of my homework for anyone who hasn't seen LISP. All in all, it is a pretty fun language to tinker with that I may end up doing some more on my on down the road.

```; Adds two numbers and returns the sum.
(+ x y))

; Returns the minimum number from a list.
(defun minimum (L)
(apply 'min L))

; Function that returns the average number of a list of numbers.
(defun average (number-list)
(let ((total 0))
(dolist (i number-list)
(setf total (+ total i)))
(/ total (length number-list))))

; Function that returns how many times an element occures in a list.
(defun count-of (x elements)
(let ((n 0))
(dolist (i elements)
(if (equal i x) (setf n (+ n 1))))
n))

; Returns the factorial of a number using an interative method.
(defun iterative-factorial (num)
(let ((factorial 1))
(dotimes (run num factorial)
(setf factorial (* factorial (+ run 1))))))

; Using a recursive method, this function returns the factorial of a number.
(defun recursive-factorial (n)
(if (<= n 0)
1
(* n (recursive-factorial (- n 1)))))

; This function calculates a number from fibonacci sequences and returns it.
(defun fibonacci (num)
(if (or (zerop num) (= num 1))
1
(let
((F1 (fibonacci (- num 1)))
(F2 (fibonacci (- num 2))))
(+ F1 F2))))

; Takes a list and returns all elements that occur on and after a symbol.
(defun trim-to (sym elements)
(member sym elements))

; Returns the ackermann of two numbers.
(defun ackermann (num1 num2)
(cond
((zerop num1) (1+ num2))
((zerop num2) (ackermann (1- num1) 1))
(t (ackermann (1- num1) (ackermann num1 (1- num2))))))

; This function defines test code for each previous function.
(defun test ()
(print (average '(1 2 3 4 5 6 7 8 9)))
(print (minimum '(5 78 9 8 3)))
(print (count-of 'a '(a '(a c) d c a)))
(print (iterative-factorial 5))
(print (iterative-factorial 4))
(print (fibonacci 6))
(print (trim-to 'c '(a b c d e)))
(print (ackermann 1 1)))

; Calls the test function.
(test)```

• 2

## Create an account

Register a new account