关于序列转换的惯用语问题

时间:2011-01-31 11:33:45

标签: clojure

我正在学习Clojure,我需要在正确的方向上推动我想出的这个问题。

我有一系列事件。每个活动都包含一个“日期”。

(def events
  [
   [1509 :marry   "Catherine of Aragon"]
   [1527 :unmarry "Catherine of Aragon"]
   [1533 :marry   "Anne Boleyn"]
   [1536 :unmarry "Anne Boleyn"]
   [1536 :marry   "Jane Seymour"]
   [1537 :unmarry "Jane Seymour"]
   [1540 :marry   "Anne of Cleves"]
   [1540 :unmarry "Anne of Cleves"]
   [1540 :marry   "Catherine Howard"]
   [1542 :unmarry "Catherine Howard"]
   [1543 :marry   "Catherine Parr"]])

我想将其转换为惰性时间轴,即每年包含一个向量的序列。从第一个事件的年份开始,并继续无限。

[[[:marry "Catherine of Aragon"]] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [[:unmarry "Catherine of Aragon"]] [] [] [] [] [] [[:marry "Ane Boleyn"]] [] [] [[:unmarry "Anne Boleyn"] [:marry "Jayne Seymour"]] ...]

2 个答案:

答案 0 :(得分:8)

(def timeline
  (let [events-by-year (group-by first events)]
    (map #(map next (events-by-year %))
      (iterate inc (reduce min (keys events-by-year))))))

快速测试:

=> (take 30 timeline)
(((:marry "Catherine of Aragon")) () () () () () () () () () () () () () () () ()
 () ((:unmarry "Catherine of Aragon")) () () () () () ((:marry "Anne Boleyn")) ()
 () ((:unmarry "Anne Boleyn") (:marry "Jane Seymour")) ((:unmarry "Jane Seymour"))
 ())

答案 1 :(得分:3)

我会建议像:

(defn timeline
  ([] (timeline (ffirst *events*) *events*))
  ([time evts]
     (let [[now later] (split-with #(= time (first %)) evts)]
       (cons (map rest now)
             (lazy-seq (timeline (inc time) later))))))

测试:

user> (take 30 (timeline))
(((:marry "Catherine of Aragon")) () () () () () () () () () () () () () () () () () 
 ((:unmarry "Catherine of Aragon")) () () () () () ((:marry "Anne Boleyn")) () () 
 ((:unmarry "Anne Boleyn") (:marry "Jane Seymour")) ((:unmarry "Jane Seymour")) ()) 

我假设事件列表也是无限的:)

更新了改进版,并从cgrand借用了一些想法(谢谢:)