Created
May 16, 2012 01:26
-
-
Save m2ym/2706563 to your computer and use it in GitHub Desktop.
reduce and mapcar
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (in-package :cl-user) | |
| (defun dot-product (lst1 lst2 &optional (acc 0)) | |
| "Computes the dot product of two sequences, represented as lists." | |
| (if (not lst1) | |
| acc | |
| (let ((x (first lst1)) | |
| (y (first lst2)) | |
| (lst11 (rest lst1)) | |
| (lst22 (rest lst2))) | |
| (dot-product lst11 lst22 (+ acc (* x y)))))) | |
| (declaim (inline mapreduce)) | |
| (defun mapreduce (reducer initial-value mapper list &rest more-lists) | |
| (declare (dynamic-extent more-lists)) | |
| (let ((acc initial-value)) | |
| (apply #'mapc | |
| (lambda (&rest args) | |
| (declare (dynamic-extent args)) | |
| (setq acc (funcall reducer acc (apply mapper args)))) | |
| list more-lists) | |
| acc)) | |
| (declaim (inline mapreduce2)) | |
| (defun mapreduce2 (reducer initial-value mapper list1 list2) | |
| (loop with acc = initial-value | |
| for x in list1 | |
| for y in list2 | |
| do (setq acc (funcall reducer acc (funcall mapper x y))) | |
| finally (return acc))) | |
| (defun dot-product1 (list1 list2) | |
| (mapreduce2 #'+ 0 #'* list1 list2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment