我是Clojure的新手,因此尝试使用clojuredocs.org中的示例数据。
;; Data
(def scenes [{:subject "Frankie"
:action "say"
:object "relax"}
{:subject "Lucy"
:action "loves"
:object "Clojure"}
{:subject "Rich"
:action "tries"
:object "a new conditioner"}])
(defn play [scenes n]
"Play a scene"
(->>
scenes
(#(get % n))
((juxt :subject :action :object))
(interpose " ")
(apply str)))
该play
功能可以正常工作:
my-stuff.core> (play scenes 0)
"Frankie say relax"
my-stuff.core> (play scenes 1)
"Lucy loves Clojure"
my-stuff.core> (play scenes 2)
"Rich tries a new conditioner"
此play-all
功能不起作用:
(defn play-all [scenes]
"Play all the scenes"
(let [x (count scenes)]
(for [n (range x)]
(map play scenes n ))))
如何更正此play-all
功能,即如何将播放功能应用于数据范围?
map
迭代一个(或多个)集合以产生一个序列。for
根据列表理解建立一个序列。你的情况,你可以使用一个或另一个。
就分解而言,实际上具有播放一个场景的功能将是有意义的:
(defn play-one [scene]
"Play a scene"
(->>
scene
((juxt :subject :action :object))
(interpose " ")
(apply str)))
然后播放第n个可以使用先例定义:
(defn play-nth [scenes n]
"Play the n(th) scene"
(->
scenes
(#(get % n))
play-one))
您可以通过多种方式播放所有场景:
(defn play-all-map1 [scenes]
"Play all the scenes"
(map (partial play-nth scenes) (range (count scenes))))
但是您可以真正简化一下,因为您不需要,range
因为scenes
可以将其视为一个序列(假设您对索引不感兴趣):
(defn play-all-map2 [scenes]
"Play all the scenes with map"
(map play-one scenes))
并带有for
:
(defn play-all-for [scenes]
"Play all the scenes with for"
(for [scene scenes]
(play-one scene)))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句