Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mod Syntax in Clojure

How do I write modulus syntax in programming language clojure?

For example the symbols money %= money_value.

like image 690
user1585646 Avatar asked Oct 25 '12 02:10

user1585646


1 Answers

There are two functions in Clojure you might want to try: mod and rem. They work the same for positive numbers, but differently for negative numbers. Here's an example from the docs:

(mod -10 3) ; => 2
(rem -10 3) ; => -1

Update:

If you really want to convert your code to Clojure, you need to realize that an idiomatic Clojure solution probably won't look anything like your JavaScript solution. Here's a nice solution that I think does roughly what you want:

(defn change [amount]
  (zipmap [:quarters :dimes :nickels :pennies]
    (reduce (fn [acc x]
              (let [amt (peek acc)]
                (conj (pop acc)
                      (quot amt x)
                      (rem amt x))))
            [amount] [25 10 5])))

(change 142)
; => {:pennies 2, :nickels 1, :dimes 1, :quarters 5}

You can look up any of the functions you don't recognize on ClojureDocs. If you just don't understand the style, then you probably need some more experience programming with higher-order functions. I think 4Clojure is a good place to start.

like image 61
DaoWen Avatar answered Sep 29 '22 10:09

DaoWen