Created
October 20, 2015 02:42
-
-
Save PuercoPop/66137175f6d1bbc5dfe2 to your computer and use it in GitHub Desktop.
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
;; Rewrite add-all for clarity why mantaining the functional approach | |
(defun add-all (list) | |
(cond | |
((null list) 0) | |
((listp (car list)) (+ (add-all (car list)) (add-all (cdr list)))) | |
((stringp (car list)) (+ (add-all (cdr list)))) | |
(t (+ (car list) (add-all (cdr list)))))) | |
;; First the ideal case | |
(defun add-pair (x y) | |
(+ x y)) | |
(reduce #'add-pair '(1 2 3)) => 6 | |
;; Now to handle strings in the lists | |
(defun zero-if-string (x) | |
(if (stringp x) | |
0 | |
x)) | |
(defun add-pair (x y) | |
(let ((x (zero-if-string x)) | |
(y (zero-if-string y))) | |
(+ x y))) | |
(reduce #'add-pair '(1 2 "s" 3)) => 6 | |
;; If there are lists inside of lists, reduce them first | |
(defun reduce-if-list (x) | |
(if (listp x) | |
(add-all x) | |
x)) | |
(defun add-pair (x y) | |
(let ((x (reduce-if-list x)) | |
(y (reduce-if-list y))) | |
(+ x y))) | |
(defun add-all (list) | |
(reduce #'add-pair list)) | |
(add-all '(1 (2 3 (4 5 6)) 3)) | |
;; Finally, we combine both cases | |
(defun add-pair (x y) | |
(let ((x (reduce-if-list (zero-if-string x))) | |
(y (reduce-if-list (zero-if-string y)))) | |
(+ x y))) | |
(add-all '(1 (2 "s" 3 (4 5 6) "x") "s" 3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment