Reputation: 45
first, i would like to understand the difference, if there is any, in the following code:
1 (setf list1 '(1 2 3))
2 (setf list2 '(10 100))
3
4 (defun som(x y )
5 (* x y))
6
7
8 (print(mapcar #'(lambda(x)x) list1))
9 (print (mapcar #'(lambda(x)x) list1))
which returns the following:
(1 2 3)
(1 2 3)
Then i would like to understand how to do the following:
(setf list1 '(1 2 3))
(setf list2 '(10 100))
(mapcar '#+ x y)
in order to get the following: ((11 101) (12 102) (13 103)), this is, add the first item of the first list to every item of the second list. Of course I could, very quickly define a function which would iterate through a list and apply a mapcar to the list. I was wondering if there is any primitive which would do that.
Thanks, have a good night
Upvotes: 1
Views: 902
Reputation: 11522
Your code
(setf list1 '(1 2 3))
(setf list2 '(10 100))
(defun som(x y )
(* x y))
(print(mapcar #'(lambda(x)x) list1))
(print (mapcar #'(lambda(x)x) list1))
;; This is the same between forms you do not need the space ;; but it is more readeable to write things with spcaes and tabs
so this is how I woul write the expression
(print (mapcar #'(lambda (x) x) list1))
or you can use the function identity
(print (mapcar #'identity list1))
allways remeber that the first element of the form is a function for the evaluator
to understand this you need to get a full understanding of lambda experssions and map functions in lisp also will be useful to learn functional programming, in that case you will wirte this as quickly as you will write the iterate version
You will have other aproches, this is not one of my foavourites because the use of global variables but it should do the thick it allways remember me to the iterative version
(defparameter *list1* '(1 2 3))
(defparameter *list2* '(10 100))
(print (mapcar (lambda (x) (mapcar (lambda (y) (+ x y)) *list2*)) *list1*))
Upvotes: 0