CS代考 COMP712 Tutorial #9: LISP – MAPCAR ans – cscodehelp代写
COMP712 Tutorial #9: LISP – MAPCAR ans
1. Using MAPCAR, write a LISP function, except-last, which given a list of lists will return a new list of lists whereby each list has its last element removed. For example:
> (except-last ‘((a b c d) (e f g) (1 2) (z)))
((a b c) (e f) (1) ())
Hint: You may wish to use butlast, a pre-defined function in LISP that given a list will return it without its last element.
(defun except-last (L) (mapcar #’butlast L))
2. Using MAPCAR, Write a LISP function, pair-list, which given two lists, will return a list of paired elements from them. For example:
· (pair-list ‘(a b c) ‘(1 2 3 4 5))
((a 1) (b 2) (c 3))
(defun pair-list (L L) (mapcar #’list L L))
3. Using MAPCAR, Write a LISP function, reverse-all, which given a list of lists will return a list of lists with each list reversed. For example:
> (reverse-all ‘((a b c d) (e f g) (1 2 3))
((d c b a) (g f e) (3 2 1))
(defun reverse-all (L) (mapcar #’reverse L))
4. Using MAPCAR, Write a LISP function, add-up, which given a list of lists of numbers will return a list of lists of the sum of those numbers:
> (add-up ‘((1 2 3) (4 5) (6 7 8 1)))
(6 9 22)
(defun add-up (L) (mapcar #’(lambda (x) (apply #’+ x)) L))
5. Write a function to compute the dot product of two sequences of numbers represented as lists. The dot product is computed by multiplying corresponding elements and then adding up the resulting products. For example:
· (dot-product ‘(10 20) ‘(3 4)) ; = 10*3 + 20*4
110
· (dot-product ‘(10 20 1) ‘(3 4 1)) ; = 10*3 + 20*4 + 1*1
111
; beautiful isn’t it?
(defun dp (L1 L2) (apply #’+ (mapcar #’* L1 L2)))
6. Using mapcar, write a function that counts all the top-level elements in a list (i.e re-write length using mapcar).
· (my-count ‘((a b) (c d) (e f)))
3
(defun my-count (L)
(apply #’+
(mapcar #’(lambda (x) 1) L)))
7. Using mapcar, write a function that computes the sum of the squares of the numbers in the list.
· (sum-squares ‘(1 2 3))
14
(defun sum-squares (L)
(apply #’+
(mapcar #’(lambda (x) (* x x)) L))
8. Write a function, no-list that given any number of arguments will return a list of only those arguments that are not a list.
· (no-list ‘(1 2 3) ‘a 2 ‘(2 4) ‘(a v))
(a 2)
(defun no-list (&rest L) (remove-if #’listp L))
9. Write a function, my-sum-odd, which given a number and a list of numbers will return the sum of all the odd numbers in the list. You should try writing a function using what you have learned in this lecture.
· (my-sum-odd ‘(1 2 3 4))
4
· (my-sum-odd ‘(2 4 6 8))
0
(defun my-sum-odd (L)
(apply #’+ (remove-if-not #’oddp L)))