Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between keep-indexed and map-indexed?

Tags:

clojure

What is the difference between map-indexed and keep-indexed?

like image 978
Dominykas Mostauskis Avatar asked Feb 11 '23 14:02

Dominykas Mostauskis


2 Answers

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))
like image 51
turingcomplete Avatar answered Feb 14 '23 02:02

turingcomplete


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)
like image 34
Shawn Zhang Avatar answered Feb 14 '23 03:02

Shawn Zhang