loops - Iterate with step and apply function -


how can pseudo-c++ code:

vector<int> vs = {...}; (i = start; < vs.size(); += step) {   vs[i] *= 10; } 

in clojure? have code:

(defn step-do [start step v]   (if (< start (count v))     (recur (+ start step) step (assoc v start (* 10 (v start))))     v))  (defn -main   [& args]   (println (step-do 2 3 (vec (range 1 15))))) 

or for variant:

(defn step-do [start step v]   (last (for [i (range start (count v) step)]           (assoc v (* 10 (v i)))))) 

what better? faster? should else?

the recur-based version fine , among fastest possible solutions, though might want use transients if it's going operate on larger vectors.

as possible alternative i'd suggest using reduce handle looping, input vector passed in initial value of accumulator , reduced sequence provided range step argument.

(defn step-do [start step v]   (reduce (fn [v i]             (assoc v (* 10 (nth v i))))           v           (range start (count v) step))) 

from repl:

(def xs (vec (range 32)))  (step-do 1 2 xs) ;= [0 10 2 30 4 50 6 70 8 90 10 110 12 130 14 150 16 170 18 190 20 210 22 230 24 250 26 270 28 290 30 310] 

this has benefit of separating selection of indices @ transformation applied (here handled range; more involved seq producer used if desired) , transformation (captured function passed reduce; generalized step-do accept a transformation function argument, rather hardwire multiply-by-10).

additionally, should quite performant (and since reduce quite central clojure's model of data handling, it's keep improving in future releases). of course here transients used speed things up.


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -