Reputation: 8125
What is the difference between map-indexed
and keep-indexed
?
Upvotes: 4
Views: 567
Reputation: 1884
Keep-indexed
will keep the result of fn
if result is not nil
(keep-indexed #(if (odd? %1) %2) [:a :b :c :d :e])
;;(:b :d)
map-indexed
will keep all result of applying fn
to coll regardless return value is nil or not
(map-indexed #(if (odd? %1) %2) [:a :b :c :d :e])
;; (nil :b nil :d nil)
Upvotes: 2
Reputation: 2188
map-indexed is like map, except that the index of each element in the coll is passed as the first arg to the function that map-indexed takes, and the element is passed as the second arg to the function.
So
(map-indexed + [1 2 3 4]) ;=> ((+ 0 1) (+ 1 2) (+ 2 3) (+ 3 4)) => (1 3 5 7)
keep-indexed works the same way as map-indexed with the difference that if (f index value) returns nil, it is not included in the resulting seq.
So for example:
(keep-indexed #(and %1 %2) [1 2 3 nil 4]) ;;=> (1 2 3 4)
You can think of keep-indexed as map-indexed wrapped in filter as follows:
(filter (complement nil?) (map-indexed f coll))
Upvotes: 6