1
该功能如何工作?特别是在这里,我无法理解juxt
的功能。Clojure中的外观顺序说明
(fn [s]
(drop 1 (iterate (fn [s]
(mapcat (juxt count first)
(partition-by identity s))) s)))
该功能如何工作?特别是在这里,我无法理解juxt
的功能。Clojure中的外观顺序说明
(fn [s]
(drop 1 (iterate (fn [s]
(mapcat (juxt count first)
(partition-by identity s))) s)))
这似乎是康威的look-and-say sequence的发电机。
这将产生序列像
(1) ; there is 1 "1" here, so...
(1 1) ; now there are 2 "1"s here, so...
(2 1) ; now there is 1 "2" and 1 "1"
(1 2 1 1) ; now there is 1 "1", 1 "2", and 2 "1"s, so...
(1 1 1 2 2 1) ; now there are 3 "1"s, 2 "2"s, and 1 "1", so ...
(3 1 2 2 1 1) ; etc.
的drop 1
去除序列输出序列的输入序列,但由于也理所当然属于外观数列,我们可以将其删除。
我们有然后是(iterate look-say initial-seq)
其中
(defn look-say [s]
(mapcat
(juxt count first)
(partition-by identity s)))
所有迭代确实是早在喂函数的输出作为输入多次,产生中间结果的序列。
要了解look-say功能,请从里到外进行操作。我们从上面的示例输出的最后一行开始,作为一个很好的例子。
(def s '(1 1 1 2 2 1))
我们要组连续的重复
(def grouped-s (partition-by identity s))
grouped-s ;=> ((1 1 1) (2 2) (1))
然后 “说” 每一组的计数
(map count grouped-s)
;=> (3 2 1)
而且我们指望
3210但我们宁愿得到点数和点数同时
(map (juxt count first) grouped-s)
;=> ([3 1] [2 2] [1 1])
几乎有项目操作,只需要连接所有这些一起
(apply concat (map (juxt count first) grouped-s))
;=> (3 1 2 2 1 1)
这是一样的
(mapcat (juxt count first) grouped-s)
;=> (3 1 2 2 1 1)
注意你也可以写为
(for [g (partition-by identity s)
f [count first]]
(f g))
;=> (3 1 2 2 1 1)
W这可能会更清楚或有助于解释前者。