Search code examples
clojureschemesicp

How does Clojure produce a positive value when a negative value is passed to this abs function?


It has been nagging me as to how cond returns a positive value in function, when a negative value is passed to its x parameter. My idea is that two negatives multiplied produce a positive, but this seems quite confusing as there appears to be no multiplication occurring anywhere in the function.

Could someone give me an detailed explanation of why a negative value passed to x returns a positive value?

(def abs
   (fn [x]
      (cond (> x 0) x
            (= x 0) 0 
            (< x 0) (- x))))

(abs -10) -> 10

The code is a variation of the abs function found in the book SICP, but written in Clojure.

Kind regards


Solution

  • When the number is negative, (< x 0), we negate it, (- x), to get a positive number of the same magnitude. You can think of negation as multiplication by -1 if you like.

    (doc -)
    -------------------------
    clojure.core/-
    ([x] [x y] [x y & more])
      If no ys are supplied, returns the negation of x, else ...