Yana Aleksieva, ID 100096302
COS 470 – Artificial Intelligence and AI Programming
Week_05
LISP Practice
-
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)
(if (or (null nums) (<= num(car nums)))
(cons num nums)
;; 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?
(cons (car nums) (insert1 num (rest nums)))
)
;; 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
insert-sort that will recursively sort a list of numbers nums
(defun insert-sort (nums)
;; define here the base case to stop the recursion:
;; if nums is empty, return an empty list
(if (null nums) '()
;; otherwise call insert1 appropriately
(insert1 (car nums) (insert-sort (cdr nums)))
)
)
-
Test your functions (use (trace insert1 insert-sort) to see how the recursion works):
insert1:
(insert1 5 '(1 2 2 4 6 7))
(1 2 2 4 5 6 7)
insert-sort:
(insert-sort '(5 3 7 5 9 2 10 4 5 6 7))
(2 3 4 5 5 5 6 7 7 9 10)
-
Write a function, ``remove,'' which takes a list and an element, and returns the original list with the first occurrence of the element removed.
Test the function with
(remove '(a 1 c 2 c 7) 'c) result (A 1 2 C 7)
-
Write a function, ``search,'' which takes a nested list and an atom, and it returns 't if it finds the atom within the nested list and returns nil otherwise.
Test the function with
(search '(a (1 c) 2 7) 'c) result: T
-
Write a function, ``sum-of-list,'' which takes a list of numbers and returns their sum. Write a similar function, ``product-of-list,'' which takes a list of numbers and returns their product.
-
Write a function called ``remainder,'' which takes two positive non-zero numbers, n and m, and returns the remainder when n is divided by m.
(defun remainder (n m)
(cond
((< n m) n)
(t (remainder (-n m) m))
)
)
Write your answers in this file, save it and submit it as a solution to the attendance check.
Share with your friends: |