Search code examples
clojurecode-snippets

Explaining this clojure syntax?


​​How​ to ​understand​ ​this ​​simple clojure code? I ​kind of ​understand​ what it is trying to do but can someone explain the syntax in great detail so I can confidently use it?

(map (fn [x] (.toUpperCase x)) (.split "Dasher Dancer Prancer" " "))


Solution

  • From Clojure REPL:

    (doc map)
    clojure.core/map
    ([f coll] [f c1 c2] [f c1 c2 c3] [f c1 c2 c3 & colls]) Returns a lazy sequence consisting of the result of applying f to the set of first items of each coll, followed by applying f to the set of second items in each coll, until any one of the colls is exhausted. Any remaining items in other colls are ignored. Function f should accept number-of-colls arguments.

    (.split "Dasher Dancer Prancer" " ") is generating a sequence of strings and each tokenized string will be passed to (fn [x] (.toUpperCase x))

    However, (fn [x] (.toUpperCase x)) is too much unnecessary typing. You can do:

    (map #(.toUpperCase %) (.split "Dasher Dancer Prancer" " "))
    

    or:

    (map (memfn toUpperCase) (.split "Dasher Dancer Prancer" " "))