Lisp two lists multiply and adding two values

这一生的挚爱 提交于 2019-12-13 06:50:07

问题


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*))


来源:https://stackoverflow.com/questions/29369587/lisp-two-lists-multiply-and-adding-two-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!