Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have a map that I want to 'expand' into an infinite sequence in the following manner:

{0 'zero 3 'three 10 'ten}
=>
('zero 'zero 'zero 'three 'three 'three 'three 'three 'three 'three 'ten 'ten 'ten ...)

the indexes of the map indicating the index of the sequence where the value should change

The following code works, but it does not please me. Can this be written in a smarter way?

(defn expand-map
  [m]
  (letfn [(em
           [last-value indexes]
           (let [value (m (first indexes))]
                (if value
                  (lazy-seq (cons value (em value (rest indexes))))
                  (lazy-seq (cons last-value (em last-value (rest indexes)))))))]
    (em 'zero (iterate inc 0))))

(take 20 (expand-map {0 'zero 3 'three 10 'ten}))
share|improve this question
oh, you want 'zero from 0th, then 'three from third, then 'ten from tenth? – andrew cooke Jul 24 '12 at 21:04
yes, another example would be {0 0 1 1 3 3} => (0 1 1 3 3 3 ...) – GHZ Jul 24 '12 at 21:07

migrated from stackoverflow.com Jul 24 '12 at 21:00

2 Answers

up vote 7 down vote accepted
(defn expand-map [m]
  (rest (reductions (fn [prev idx]
                      (get m idx prev))
                    'zero
                    (range))))
share|improve this answer
heh, that's cute. – andrew cooke Jul 24 '12 at 22:26
(defn expand-map [m]
  (let [m (into (sorted-map) m)]
    (map #(-> m (rsubseq <= %) first val) (range))))
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.