I am new to Clojure, and I have been translating some of the data processing work I have done recently as an aid to learning. I have a function translation that works fine, and is shorter, but looks much less readable. Can anyone suggest a more readable and / or more idiomatic way to handle this?
In Python:
def createDifferenceVector(v,startWithZero=True): deltas = [] for i in range(len(v)): if i == 0: if startWithZero: deltas.append(0.0) else: deltas.append(v[0]) else: deltas.append(v[i] - v[i-1]) return deltas
My attempt to translate Clojure:
(defn create-diff-vector [v start-zero] (let [ext-v (if start-zero (cons (first v) v) (cons 0 v))] (for [i (range 1 (count ext-v))] (- (nth ext-v i) (nth ext-v (- i 1))))))
Maybe this is less readable just because of my inexperience with Clojure, but in particular, the trick of adding an element to the input vector feels to me as if it hides the intention. All the solutions I tried that didn't use the pre-release trick were much longer and uglier.
Many sequence transformations are incredibly elegant in Clojure, but the ones that I still find difficult are ones like this one that a) are manipulated by an index rather than an element, and / or b) require special handling of certain elements.
Thanks for any suggestions.
functional-programming clojure
eggsyntax
source share