Reputation: 726
How do we loop through a list to get the absolute value of each list item using lambda
or any other looping mechanism?
(defun span (start end &key (step 1))
(loop for n from start to end by step
collect n))
(setf bce #'(lambda (x) (abs x)) (span -10 -1))
The result can be used, for example, as the BCE timeline.
Upvotes: 0
Views: 234
Reputation: 27424
You can use mapcar
(reference):
CL-USER> (mapcar #'(lambda (x) (abs x)) (span -10 -1))
(10 9 8 7 6 5 4 3 2 1)
;; can be written also as:
CL-USER> (mapcar (lambda (x) (abs x)) (span -10 -1))
(10 9 8 7 6 5 4 3 2 1)
;; better yet:
CL-USER> (mapcar #'abs (span -10 -1))
(10 9 8 7 6 5 4 3 2 1)
As loop:
CL-USER> (loop for x in (span -10 -1) collect (abs x))
(10 9 8 7 6 5 4 3 2 1)
Combining this in a single function:
CL-USER> (defun span (start end &key (step 1) (key #'identity))
(loop for n from start to end by step
collect (funcall key n)))
SPAN
CL-USER> (span -10 -1)
(-10 -9 -8 -7 -6 -5 -4 -3 -2 -1)
CL-USER> (span -10 -1 :key #'abs)
(10 9 8 7 6 5 4 3 2 1)
Upvotes: 5