diff options
-rw-r--r-- | chickadee/math.scm | 30 |
1 files changed, 28 insertions, 2 deletions
diff --git a/chickadee/math.scm b/chickadee/math.scm index 753f70d..3bcda52 100644 --- a/chickadee/math.scm +++ b/chickadee/math.scm @@ -16,11 +16,37 @@ ;;; <http://www.gnu.org/licenses/>. (define-module (chickadee math) - #:export (clamp)) + #:export (square + clamp + min + max) + #:replace (min max)) -(define (clamp min max x) +(define-inlinable (square x) + (* x x)) + +(define-inlinable (clamp min max x) "Restrict X to the range defined by MIN and MAX. Assumes that MIN is actually less than MAX." (cond ((< x min) min) ((> x max) max) (else x))) + +;; Some macro trickery to inline calls to min/max with 2 arguments. +;; We often call min/max on floating point values, so inlining such +;; calls allows the compiler to unbox many of these operations, +;; reducing allocation. +(define-syntax min + (syntax-rules () + ((_ a b) + (if (< a b) a b)) + ((_ a b ...) + (let ((m (min b ...))) + (if (< a m) a m))))) + +(define-syntax max + (syntax-rules () + ((_ a b) (if (> a b) a b)) + ((_ a b ...) + (let ((m (max b ...))) + (if (> a m) a m))))) |