It depends on the form of your algorithm. In general, higher-level constructs are more understandable than explicit recursion, but sometimes the form of the problem makes this less clear.
Other notes:
rest returns a sequence, not a list. It doesnβt matter here.
You must use destructuring. For instance:
(let [x1 (first (first vertices)) x2 (first (second vertices)) y1 (second (first vertices)) y2 (second (second vertices))
This can be replaced by:
(let [[x1 y1] [x2 y2]] vertices] ... )
However, this is not a very complicated algorithm to implement with reduce :
(defn inc-dec "Convenience function for incrementing and decrementing" ([condition i] (if condition (inc i) (dec i))) ([condition i amount] (if condition (+ i amount) (- i amount)))) (defn winding-num [poly point] (let [translated-poly (map #(map - % point) poly) winding-reducer (fn winding-reducer [w [[x1 y1] [x2 y2]]] (cond (and (< (* y1 y2) 0) ; r (> (+ x1 (/ (* y1 (- x2 x1)) (- y1 y2))) 0)) (inc-dec (< y1 0) w) (and (zero? y1) (> x1 0)) (inc-dec (> y2 0) w 0.5) (and (zero? y2) (> x2 0)) (inc-dec (< y1 0) w 0.5) :else w)) ] (reduce winding-reducer 0 (partition 2 1 translated-poly))))
source share