Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this function which reverses the interleave process into x number of subsequences

Tags:

clojure

I completed exercise 43 on 4clojure the other day and checked some of the other solutions. One in particular has confused me.

The challenge asks you to write a function which satisfies all of these:

(= (__ [1 2 3 4 5 6] 2) '((1 3 5) (2 4 6)))
(= (__ (range 9) 3) '((0 3 6) (1 4 7) (2 5 8)))
(= (__ (range 10) 5) '((0 5) (1 6) (2 7) (3 8) (4 9)))

My solution was this:

(fn [l n] 
    (map #(map second %) (vals (group-by #(mod (first %) n) 
    (map vector (iterate inc 0) l)))))

User himself had this solution: #(apply map list (partition %2 %1)) and I couldn't work out how it worked.

Let's work through the first problem:

(= (__ [1 2 3 4 5 6] 2) '((1 3 5) (2 4 6)))

well the (#(partition %2 %1) [1 2 3 4 5 6] 2) would give us ((1 2) (3 4) (5 6)) now how does apply map list on that produce (1 3 5) (2 4 6)

like image 359
Ravi Avatar asked Jan 18 '23 17:01

Ravi


1 Answers

apply is using the ((1 2) (3 4) (5 6)) as a variable length list of additional arguments. Then iteration of the map is applying the list function to all three of these additional lists.

As a result it expands as follows:

   (apply map list '((1 2) (3 4) (5 6)))
=> (map list '(1 2) '(3 4) '(5 6))
=> (list 1 3 5) and (list 2 4 6)
like image 51
mikera Avatar answered Jan 20 '23 07:01

mikera