How do I translate an while loop to clojure code -


for example, extended euclidean algorithm (quoted wiki):

function extended_gcd(a, b)     x := 0    lastx := 1     y := 1    lasty := 0     while b ≠ 0         quotient := div b         (a, b) := (b, mod b)         (x, lastx) := (lastx - quotient*x, x)         (y, lasty) := (lasty - quotient*y, y)            return (lastx, lasty) 

which tried , got:

 (defn extended-gcd    [a b]   (loop [a b b x 0 y 1 lx 1 ly 0]      (if (zero? b)       [lx ly]       (recur b (mod b)              (- lx (* (int (/ b)) x))              (- ly (* (int (/ b)) y))              x y)))) 

i guess find way translate loops deal sequence. how one? how write in clojure way? map, reduce, etc. rather loop recur.

for extended euclidean algorithm can use simple recursion, makes function quite elegant:

(defn extended-gcd [a b]   (if (zero? b) [1 0]     (let [[q r] [(quot b) (rem b)]           [s t] (extended-gcd b r)]        [t (- s (* q t))]))) 

let's try it:

user=> (extended-gcd 120 23) [-9 47] 

not problems need solved using map/reduce/sequence. argue above clojure way "(reduce + [1 2 3 4 5])" type of answer looking for.


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -