2014-09-04 73 views

回答

3

這似乎是康威的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-sa​​y功能,請從裏到外進行操作。我們從上面的示例輸出的最後一行開始,作爲一個很好的例子。

(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這可能會更清楚或有助於解釋前者。