mapsplice

utilities — cgrand, 25 March 2009 @ 22 h 11 min

I needed to update a seq as follows: apply a given function to items at specified indices and insert the result (a seq) in place.
My first laborious attempt involved extracting subseqs of untouched items, mapping the function on the remaining items then joining everything back. Bleh! (Really, I don’t like indices but this time I haven’t found a way to work around.)
I was sad when, suddenly, I found this shortest solution:

(defn mapsplice [f coll indices]
  (let [need-splice (map (set indices) (iterate inc 0))]
    (mapcat #(if %2 (f %1) [%1]) coll need-splice)))
;; (mapsplice #(repeat % %) (range 10) [7 3])
;; (0 1 2 3 3 3 4 5 6 7 7 7 7 7 7 7 8 9)

Simple variations on state machines in Clojure

unsorted — cgrand, 3 March 2009 @ 15 h 00 min

Given a transition function that takes the current state and an input value as arguments then (reduce transition-fn initial-state input) returns the final state.

If you are interested in intermediate states, you can use clojure.contrib.seq-utils/reductions instead of reduce.

If you want an asynchronous state machine, you can use an agent:

(def agt (agent initial-state))
;then each time you get an input-value:
(send agt transition-fn input-value)

If you add a watch to the agent, you can react to state transitions.

(c) 2024 Clojure and me | powered by WordPress with Barecity