Lisp two lists multiply and adding two values

2019-08-29 01:32发布

问题:

I have two lists, each list has lists inside of them. I want to get the third value from the first list and the first value from the second list each time, multiply these items and then add them to sum.

(defvar *list-1* ((item1 1 4) (item2 4 5) (item3 5 8)))
(defvar *list-2* ((1) (3) (5)))

So I want (1*4) + (3*5) + (5*8) = 59

I have the below code so far

(defun get-total (lst lst1)
  (loop :for element :in lst 
        :for element1 :in lst1 
        :sum (third element)))

回答1:

loop can do some destructuring for you, so you don't even need to call third, but can just loop for (nil nil a) in the first list, which will bind a to the third value. You can do the same thing with the second list, except with a destructuring list list (b). Then you'd have:

(loop :for (nil nil a)  :in '((item1 1 4) (item2 4 5) (item3 5 8)) 
      :for (b)          :in '((1) (3) (5))
      :summing (* a b))
;=> 59


回答2:

Even though Joshuas loop with destructuring is quite neat I thought I'd add how to change your code to do the same without:

(defun get-total (lst1 lst2)      
  (loop :for element1 :in lst1 
        :for element2 :in lst2
        :sum (* (third element1) (first element2)))


回答3:

And just for fun, here is a non-loop version

(reduce #'+ (mapcar #'* (mapcar #'third *list-1*)
                        (mapcar #'first *list-2*)))

and another

(reduce #'+ (mapcar (lambda (x y) (* (third x) (first y)))
                    *list-1* *list-2*))