1
0
mirror of https://github.com/janet-lang/janet synced 2024-11-28 19:19:53 +00:00

Merge pull request #1266 from primo-ppcg/min-max

Speed up `min`, `max`
This commit is contained in:
Calvin Rose 2023-08-21 22:32:03 -05:00 committed by GitHub
commit 70a467d469
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -702,30 +702,38 @@
[f] [f]
(fn [x] (not (f x)))) (fn [x] (not (f x))))
(defmacro- do-extreme
[order args]
~(do
(def ds ,args)
(var k (next ds nil))
(var ret (get ds k))
(while (,not= nil (set k (next ds k)))
(def x (in ds k))
(if (,order x ret) (set ret x)))
ret))
(defn extreme (defn extreme
``Returns the most extreme value in `args` based on the function `order`. ``Returns the most extreme value in `args` based on the function `order`.
`order` should take two values and return true or false (a comparison). `order` should take two values and return true or false (a comparison).
Returns nil if `args` is empty.`` Returns nil if `args` is empty.``
[order args] [order args] (do-extreme order args))
(var [ret] args)
(each x args (if (order x ret) (set ret x)))
ret)
(defn max (defn max
"Returns the numeric maximum of the arguments." "Returns the numeric maximum of the arguments."
[& args] (extreme > args)) [& args] (do-extreme > args))
(defn min (defn min
"Returns the numeric minimum of the arguments." "Returns the numeric minimum of the arguments."
[& args] (extreme < args)) [& args] (do-extreme < args))
(defn max-of (defn max-of
"Returns the numeric maximum of the argument sequence." "Returns the numeric maximum of the argument sequence."
[args] (extreme > args)) [args] (do-extreme > args))
(defn min-of (defn min-of
"Returns the numeric minimum of the argument sequence." "Returns the numeric minimum of the argument sequence."
[args] (extreme < args)) [args] (do-extreme < args))
(defn first (defn first
"Get the first element from an indexed data structure." "Get the first element from an indexed data structure."