这个功能是如何工作的?特别是,我在这里很难理解juxt的功能。
(fn [s]
(drop 1 (iterate (fn [s]
(mapcat (juxt count first)
(partition-by identity s))) s)))发布于 2014-09-04 20:40:01
这似乎是康威的看-说顺序的生成器。
这会产生类似的序列
(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)))所有迭代操作都是将函数的输出作为输入反复输入,生成中间结果的序列。
要理解表象的功能,从内到外工作。让我们从上面示例输出的最后一行开始,作为一个很好的例子。
(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)但同时我们也在计算
(map first grouped-s)
;=> (1 2 1)但我们宁愿同时计数和项目
(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)这可能更清楚或者有助于解释前者。
https://stackoverflow.com/questions/25674037
复制相似问题