Yana Aleksieva ID 100096302
COS 470 – Artificial Intelligence and AI Programming
Week_04
LISP Practice

Write a recursive function in LISP to calculate the factorial of a given positive number num:
(defun fact ( num )
;; base case if num=0 return 1
;; otherwise – accumulate the product recursively
)
(defun fact ( num )
(if (= num 0) 1
(* num (fact(1 num))
)))

Consider the following Lisp expression (function definition):
(defun pow(bas ex)
(if (= bas 0) 1
(* bas (pow bas (1 ex)))))

What this function is supposed to do?

Copy/paste it in clisp interpreter.

Run it:
(pow 0 5) Write the result here:
1
(pow 2 5) Explain the error message.
***  handle_fault error2 ! address = 0x1 not in [0x2042d004,0x20593bfc) !
SIGSEGV cannot be cured. Fault address = 0x1.
Permanently allocated: 91840 bytes.
Currently in use: 2242576 bytes.
Free space: 236016 bytes.
Segmentation fault

Correct the function definition to produce a correct result:
(defun pow(bas ex)
(if (or (= bas 0) (= ex 0)) 1
(* bas (pow bas (1 ex)))))
Try delete function in LISP:
(delete 1 '( 2 1 4 1 3 1 1 4 5 6 2 ))
(delete 'b '( a b c d b s e d q b s z b b ))
Explain what this function is supposed to do:

Using LISP function delete, create a LISP function uniq that will take one argument of type list and will return a list with the unique elements:
Example:
(uniq '(1 2 4 5 7 3 2 7 6 5 7 7 7))
(1 2 4 5 7 3 6)
Copy your solution here:
(defun uniq (list)
(cond
((null list) '())
((t (cons (car list) (uniq (delete (car list) list)))))
)

Create a recursive LISP function named insert1 that will insert a number num into a sorted in increasing order list of numbers nums
(defun insert1 (num nums)
;; num is a number
;; nums is a list of numbers (sorted in increasing order)
;; define here the base case to stop the recursion:
;; if nums is empty or if num is <= than the first element
;; in nums
;; then the function returns a list constructed by num and
;; the list nums which constructor will you use?
;; if it is not the base case  make a recursion
;; construct a list with the first element from nums and
;; the result of
;; calling the insert1 function with num and the rest of
;;nums (cdr nums)
)

Use the insert1 function created on the previous step to create a LISP function
insertsort that will recursively sort a list of numbers nums
(defun insertsort (nums)
;; define here the base case to stop the recursion:
;; if nums is empty, return an empty list
;; otherwise call insert1 appropriately
)

Test your functions (use (trace insert1 insertsort) to see how the recursion works):
insert1:
(insert1 5 '(1 2 2 4 6 7))
insertsort:
(insertsort '(5 3 7 5 9 2 10 4 5 6 7))
Write your answers in this file, save it and submit it as a solution to the attendance check. 