解释这个clojure语法?
怎样 到懂 这简单的clojure代码? 我有点懂 它试图做什么,但是有人能详细解释一下语法,这样我就可以自信地使用它了吗解释这个clojure语法?,clojure,code-snippets,Clojure,Code Snippets,怎样 到懂 这简单的clojure代码? 我有点懂 它试图做什么,但是有人能详细解释一下语法,这样我就可以自信地使用它了吗 (map (fn [x] (.toUpperCase x)) (.split "Dasher Dancer Prancer" " ")) 来自Clojure回复: 文档映射 clojure.core/map [f coll][f c1 c2][f c1 c2 c3][f c1 c2 c3&colls] 返回一个惰性序列,该序列由将f应用于 每个c
(map (fn [x] (.toUpperCase x)) (.split "Dasher Dancer Prancer" " "))
来自Clojure回复:
文档映射
clojure.core/map
[f coll][f c1 c2][f c1 c2 c3][f c1 c2 c3&colls]
返回一个惰性序列,该序列由将f应用于
每个coll的第一个项目集,然后将f应用于该集合
每个coll中的第二项,直到任何一个coll
筋疲力尽的忽略其他Coll中的任何剩余项。作用
f应该接受colls参数的数量
.split Dasher Dancer Prancer正在生成一系列字符串,每个标记化的字符串将传递给fn[x]。toUpperCase x
但是,fn[x].toUpperCase x太多不必要的键入。你可以做:
(map #(.toUpperCase %) (.split "Dasher Dancer Prancer" " "))
或:
这是将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
你能更具体地说明你不理解的内容吗?同样地,你已经理解的内容吗?它真的只是您需要解释的语法,或者,例如,Java互操作原语?lambdas的概念?地图精确点。@CharlesDuffy我只需要了解整体概念,split是如何跟随我的toUpperCase发生的?您正在推广使用类型提示以避免反射。但这通常是不必要的,除非通过使用类型提示证明算法的性能更好。Clojure在不提供类型提示的情况下效率高、速度快。@Chiron我建议只在特定情况下使用类型提示,因为它实际上可以避免反射实例;如果你用*反射警告*,它会支持我。大多数被过度使用的地方都是根本不需要或者没有任何好处的地方。回答得好。如果我使用一种方法接着使用另一种方法,我必须使用地图吗?对不起,我对clojure很陌生,所以我有这么多疑问。如果我必须在这两个方法中的任何一个中再加一个空的检查,我该怎么办。@javaguy您不必使用map;它通常是完成这项工作的最佳工具。如果您想做其他事情,您可以为表单编写一个等价物,或者一个循环构建一个懒惰的seq,或者。。。好吧,随你的便。花点时间读一本书来帮助我们分解这里的概念可能是值得的。这确实是一个很好的答案。如果我使用一种方法接着使用另一种方法,我必须使用地图吗?对不起,我对clojure很陌生,所以我有这么多疑问。如果我必须在这两种方法中的任何一种中放入另一个空检查,我必须做什么。
(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