Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"apply map vector" idiom - How happens to be 2 functions?

Tags:

clojure

Here is a sample from my mini code where I copied from clojure docs site.

(apply map vector (vec jpgList)) 

I guess map and vector are both functions, but apply takes only one function. How come in here apply takes two functions?

like image 857
ᐅdevrimbaris Avatar asked Apr 30 '13 13:04

ᐅdevrimbaris


1 Answers

Read the documentation of apply:

user=> (doc apply)
-------------------------
clojure.core/apply
([f args] [f x args] [f x y args] [f x y z args] [f a b c d & args])
  Applies fn f to the argument list formed by prepending intervening arguments to args.
nil

So, (apply map vector (vec jpgList)) corresponds to f x args, so map will be applied to the the function vector, followed by the elements of (vec jpgList). Unlike Haskell, Clojure's map supports multiple collections to operate on. (vec jpgList) presumably is a nested vector, or list, like in the following example:

user=> (apply map vector [[1 2 3] [4 5 6]])
([1 4] [2 5] [3 6])  

What happened is, every element produced by map is the vector of each nth element of the elements of the nested vector. This function is also known as transpose in matrix operations.

like image 160
Michiel Borkent Avatar answered Sep 21 '22 06:09

Michiel Borkent