Last active
November 22, 2016 21:59
-
-
Save worldofchris/5540410 to your computer and use it in GitHub Desktop.
Figuring out the difference between map and apply in Clojure...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; Define a vector of vectors | |
(def input [[1,2,3],[1,3,4],[1,5,6]]) | |
; Calling the 'list' function on this: | |
user=> (list input) | |
; Gives us a single item list whose one and only member is this | |
; vector of vectors: | |
([[1 2 3] [1 3 4] [1 5 6]]) | |
; Mapping the 'list' function to input _applies_ | |
; 'list' to the set of first items in input, followed by applying it to the set | |
; of second items in input, followed by applying it to the set of third items: | |
user=> (map list input) | |
; This gives us a list whose members are single element lists, where the single | |
; element is the vector list was mapped to. | |
(([1 2 3]) ([1 3 4]) ([1 5 6])) | |
; But if we 'apply' the 'map list' function to the input collection: | |
user=> (apply map list input) | |
; Then 'apply' extracts the vectors from the vector of vectors to create | |
; an argument list which is then passed to 'map list': | |
((1 1 1) (2 3 5) (3 4 6)) | |
; If we were to do the unpacking by hand we and then pass the individual | |
; vectors to map list: | |
user=> (map list [1,2,3],[1,3,4],[1,5,6]) | |
; we'd get the same result: | |
((1 1 1) (2 3 5) (3 4 6)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment