(system-include "carp_int.h") (doc Int "is the default integral data type.") (defmodule Int (register + (λ [Int Int] Int)) (register - (λ [Int Int] Int)) (register * (λ [Int Int] Int)) (register / (λ [Int Int] Int)) (register < (λ [Int Int] Bool)) (register > (λ [Int Int] Bool)) (register = (λ [Int Int] Bool)) (register copy (λ [&Int] Int)) (register inc (λ [Int] Int)) (register dec (λ [Int] Int)) (register neg (λ [Int] Int)) (register mod (λ [Int Int] Int)) (doc to-int "acts as the identity function to implement the interface.") (sig to-int (Fn [Int] Int)) (defn to-int [a] a) (doc from-int "acts as the identity function to implement the interface.") (sig from-int (Fn [Int] Int)) (defn from-int [a] a) (implements + Int.+) (implements - Int.-) (implements * Int.*) (implements / Int./) (implements < Int.<) (implements > Int.>) (implements = Int.=) (implements copy Int.copy) (implements inc Int.inc) (implements dec Int.dec) (implements neg Int.neg) (implements mod Int.mod) (implements to-int Int.to-int) (implements from-int Int.from-int) ) (defmodule Int (register MAX Int "CARP_INT_MAX") (register MIN Int "CARP_INT_MIN") (register bit-shift-left (λ [Int Int] Int)) (register bit-shift-right (λ [Int Int] Int)) (register bit-and (λ [Int Int] Int)) (register bit-or (λ [Int Int] Int)) (register bit-xor (λ [Int Int] Int)) (register bit-not (λ [Int] Int)) (implements bit-shift-left Int.bit-shift-left) (implements bit-shift-right Int.bit-shift-right) (implements bit-and Int.bit-and) (implements bit-or Int.bit-or) (implements bit-xor Int.bit-xor) (implements bit-not Int.bit-not) (doc abs "The absolute value (removes the negative sign) of an Int.") (register abs (λ [Int] Int)) (implements abs Int.abs) (defn even? [a] (= (mod a 2) 0)) (defn odd? [a] (not (even? a))) (defn zero [] 0) (implements zero Int.zero) (defn add-ref [x y] (Int.+ @x @y)) ;; Move to generic math module? (defn clamp [min, max, val] (if (> val max) max (if (< val min) min val))) (doc pow "Raise x to the power of y.") (defn pow [x y] (let-do [r 1] (while (/= y 0) (do (when (/= (bit-and y 1) 0) (set! r (* r x))) (set! y (/ y 2)) (set! x (* x x)))) r)) (doc positive-mod "Like mod but always returns a positive answer.") (defn positive-mod [k n] (let [r (Int.mod k n)] (if (> 0 r) (+ r n) r))) (implements add-ref Int.add-ref) (implements pow Int.pow) ) (defmodule IntRef (defn = [a b] (Int.= @a @b)) (implements = IntRef.=) (defn < [a b] (Int.< @a @b)) (implements < IntRef.<) (defn > [a b] (Int.> @a @b)) (implements > IntRef.>) )