Please write the following functions in LISP with instructions given below. Plea
ID: 3908450 • Letter: P
Question
Please write the following functions in LISP with instructions given below. Please include a brief explanation of the code you post for each question.
1. Create a function WEIGHT-OF-PURCHASE that computes the sum of the weights from a shopping list. The shopping list has two sublists with the weight of the item as the second element. Examples:
(WEIGHT-OF-PURCHASE '((MILK 1000 GRAMS) (SUGAR 500 GRAMS))) (Links to an external site.)Links to an external site.
1500
(WEIGHT-OF-PURCHASE '((FLOUR 500 GRAMS) (CHEESE 100 GRAMS))) (Links to an external site.)Links to an external site.
600
2. Define a function INSERT-BEHIND, which, in contrast to CONS, inserts a LISP expression into the back of a list instead of the front. Examples:
(INSERT-BEHIND '(FOOTBALL) '(I LIKE)) (Links to an external site.)Links to an external site.
(I LIKE (FOOTBALL))
(INSERT-BEHIND 'DIFFICULT '(LISP IS NOT)) (Links to an external site.)Links to an external site.
(LISP IS NOT DIFFICULT)
3. Write a predicate SAFE-LESSP that has two arguments and firstly makes certain that it is dealing with two numbers. If the first number is smaller than the second, T should be returned, otherwise return NIL.
4. Write a function WHAT-IS-IT that accepts an argument and returns what it is. In case of a number return NUMBER, in case of a symbol return S-ATOM, and in case of a list return LIST. If it is none of these, return DO-NOT-KNOW. Examples:
(WHAT-IS-IT "THIS IS A STRING") (Links to an external site.)Links to an external site.
DO-NOT-KNOW
(WHAT-IS-IT 2) (Links to an external site.)Links to an external site.
NUMBER
5. Define a recursive function ALL-SAME-AS-ELEMENT that has two arguments, an atom and a list. ALL-SAME-AS-ELEMENT should test whether all the elements in the list are the same as the atom. Should this be the case, the value returned should be T, otherwise NIL. Examples:
(ALL-SAME-AS-ELEMENT 'X '(X X X)) (Links to an external site.)Links to an external site.
T
(ALL-SAME-AS-ELEMENT 'Y '(X Y X)) (Links to an external site.)Links to an external site.
NIL
Explanation / Answer
Lisp:
1. (defun WEIGHT-OF-PURCHASE(lst) (if (null lst) 0
(+ ( car (cdr (car lst))) (WEIGHT-OF-PURCHASE (cdr lst)) )
))
2. (defun INSERT-BEHIND(x lst)
(if (null lst) (cons x '())
(cons (car lst ) (INSERT-BEHIND x (cdr lst)) ) ))
3. (defun SAFE-LESSP(n1 n2) (
if (and (numberp n1) (numberp n2) )
(if (< n1 n2) t nil)
(write 'NOT_NUMBER)
))
4. (defun WHAT-IS-IT(x) (if (numberp x) (write 'NUMBER)
(if (symbolp x) (write 'S-ATOM)
(if (listp x) (write 'LIST)
(write 'DO-NOT-KNOW))))
5. (defun ALL-SAME-AS-ELEMENT(x lst) (if (null lst) t (if (equal x (car lst)) (ALL-SAME-AS-ELEMENT x (cdr lst)) nil)))