7

How do I write modulus syntax in programming language clojure?

For example the symbols money %= money_value.

Jonik
  • 80,077
  • 70
  • 264
  • 372
user1585646
  • 421
  • 1
  • 4
  • 16

1 Answers1

11

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.

DaoWen
  • 32,589
  • 6
  • 74
  • 101
  • How about this in clojure... var change = function (amount) { var QUARTER_VALUE = 25, DIME_VALUE = 10, NICKEL_VALUE = 5; var quarters = Math.floor(amount / QUARTER_VALUE); amount %= QUARTER_VALUE; var dimes = Math.floor(amount / DIME_VALUE); – user1585646 Oct 25 '12 at 02:44
  • @user1585646 that's not clojure? – Pointy Oct 25 '12 at 02:51
  • I know but i want to convert it to clojure. – user1585646 Oct 25 '12 at 02:54
  • That's a different question. Also, I think you're missing code. As it stands, I'm not sure that makes any sense. – Rayne Oct 25 '12 at 02:59
  • 1
    @user1585646 - There you go, now you have a Clojure version! (I've updated my answer.) – DaoWen Oct 25 '12 at 06:15