1
0
mirror of https://github.com/janet-lang/janet synced 2024-06-16 10:19:55 +00:00

speed up min, max

This commit is contained in:
primo-ppcg 2023-08-21 12:50:53 +07:00
parent ee01045db5
commit 6e8979336d

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."