Hey Olivier, You can shorten the body of your function with nil-punning and in lining next-time (rather than explicitly letting it), e.g:
(if (empty? events) timed-events (let [current (first events) next-time (+ (:duration current) time)] (recur next-time (conj timed-events (assoc current :time time)) (rest events))) To: (if-let [current (first remaining)] (recur (conj (+ (:duration current) time) timed-events (assoc current :time time)) (rest events)) timed-events) As a style thing, you might choose to be explicit about the loop/recur, rather than having a multi-arity fn, e.g (defn to-timed-events [events] (loop [result [] remaining events time 0] (if-let [current (first remaining)] (recur (conj result (assoc current :time time)) (rest remaining) (+ (:duration current) time)) result))) Derek On Sunday, April 24, 2016 at 8:01:14 PM UTC+10, Olivier Scalbert wrote: > > Hi all, > > I am a Clojure beginner .... > And I have an advice to ask ! > > I have an array of events: > > (def events [ > {:id "1" :duration 100} > {:id "2" :duration 200} > {:id "3" :duration 300} > ]) > > I wanted to transform this array into: > [ > {:id 1, :duration 100, :time 0} ; event 1 starts at 0 > {:id 2, :duration 200, :time 100} ; event 2 starts when event 1 is > finished, so at 100 > {:id 3, :duration 300, :time 300} ; event 3 starts when event 2 is > finished, so at 100 + 200 > ] > > Here is the function code: > > (defn to-timed-events > ([time events] (to-timed-events time [] events)) > ([time timed-events events] > (if (empty? events) > timed-events > (let [current (first events) > next-time (+ (:duration current) time)] > (recur next-time (conj timed-events (assoc current :time > time)) (rest events)) > )))) > > It seems to work, but it looks a bit long for what it is doing. Is it > possible to improve it ? > > Thanks for your help, > > Olivier > -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups "Clojure" group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.