Thursday, August 11, 2011

Counting number representations

We can define the counting numbers based upon successive calls to the inc function:

(defn expand-number*

  (if (zero? n)
    (cons inc (list (expand-number* (dec n))))))

(defmacro expand-number

  (expand-number* n))

We can also define them in terms of the unary numeral system:

(defmacro tally-marks

  (cons + (map (constantly 1) (range 0 n))))

Here is how these functions work:

(= (macroexpand-1 '(expand-number 5))
   `(inc (inc (inc (inc (inc 0))))))

(= (macroexpand-1 '(tally-marks 5))
   `(+ 1 1 1 1 1))

No comments:

Post a Comment