解释这个clojure语法?

时间:2013-08-24 21:52:48

标签: clojure code-snippets

如何理解这个简单的clojure代码? 我有点理解它想要做什么,但是有人可以非常详细地解释语法,所以我可以自信地使用它吗?

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

2 个答案:

答案 0 :(得分:5)

来自Clojure REPL:

  

(doc map)
  clojure.core /图
  ([f coll] [f c1 c2] [f c1 c2 c3] [f c1 c2 c3& colls])     返回一个惰性序列,包含将f应用于的结果     每个coll的第一项的集合,然后将f应用于集合     每个coll中的第二个项目,直到任何一个colls     累。其他colls中的任何剩余项都将被忽略。功能     f应该接受colls of colls参数。

(。split“Dasher Dancer Prancer”“”)正在生成一系列字符串,每个标记化字符串将传递给(fn [x](。toUpperCase x))< / strong>

然而,(fn [x](。toUpperCase x))是太多不必要的打字。你可以这样做:

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

或:

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

答案 1 :(得分:4)

这是定义一个lambda(一个匿名函数,在其单个参数上调用toUpperCase),并将它(使用map)应用于String.split()的每个结果。

map接受一个函数和一系列事物来应用该函数,并返回一系列结果,将函数应用于输入序列。

以下将操作分解为更小的部分:

(defn upper-case-fn [^String x]
  "this makes the same function, but not anonymous, and provides a type hint
  (making it more efficient by avoiding the need for reflection)."
  (.toUpperCase x))

;; you could also write the above like so:
(def upper-case-fn (fn [x] (.toUpperCase x)))

(def input-seq
  "this assigns your input seq to a var; in the real world, with dynamic data,
   you wouldn't do this"
  (.split "Dasher Dancer Prancer" " "))

(def output-seq
  "this is precisely the same as your sample, except that it's using a named
  function rather than an anonymous one, and assigns the output to a var"
  (map upper-case-fn input-seq))

;; if you enter this at a repl, you're looking at the contents of this var
output-seq