1
0
mirror of https://github.com/janet-lang/janet synced 2025-01-26 15:16:51 +00:00

Improve product and sum

This commit is contained in:
Calvin Rose 2018-07-09 23:29:15 -04:00
parent 1acd2d1de7
commit e777dc4304

View File

@ -96,8 +96,6 @@
:table true :table true
:struct true}) :struct true})
(fn [x] (not (get non-atomic-types (type x)))))) (fn [x] (not (get non-atomic-types (type x))))))
(defn sum [xs] (apply1 + xs))
(defn product [xs] (apply1 * xs))
# C style macros and functions for imperative sugar # C style macros and functions for imperative sugar
(defn inc [x] (+ x 1)) (defn inc [x] (+ x 1))
@ -214,6 +212,37 @@
(array.concat accum body) (array.concat accum body)
(apply1 tuple accum)) (apply1 tuple accum))
(defmacro and
"Evaluates to the last argument if all preceding elements are true, otherwise
evaluates to false."
[& forms]
(def len (length forms))
(if (= len 0)
true
((fn aux [i]
(cond
(>= (inc i) len) (get forms i)
(tuple 'if (get forms i) (aux (inc i)) false))) 0)))
(defmacro or
"Evaluates to the last argument if all preceding elements are false, otherwise
evaluates to true."
[& forms]
(def len (length forms))
(if (= len 0)
false
((fn aux [i]
(def fi (get forms i))
(if
(>= (inc i) len) fi
(do
(if (atomic? fi)
(tuple 'if fi fi (aux (inc i)))
(do
(def $fi (gensym))
(tuple 'do (tuple 'def $fi fi)
(tuple 'if $fi $fi (aux (inc i))))))))) 0)))
(defmacro loop (defmacro loop
"A general purpose loop macro." "A general purpose loop macro."
[head & body] [head & body]
@ -296,36 +325,15 @@
(tuple.prepend body 'do))) (tuple.prepend body 'do)))
$accum)) $accum))
(defmacro and (defn sum [xs]
"Evaluates to the last argument if all preceding elements are true, otherwise (var accum 0.0)
evaluates to false." (loop [x :in xs] (+= accum x))
[& forms] accum)
(def len (length forms))
(if (= len 0)
true
((fn aux [i]
(cond
(>= (inc i) len) (get forms i)
(tuple 'if (get forms i) (aux (inc i)) false))) 0)))
(defmacro or (defn product [xs]
"Evaluates to the last argument if all preceding elements are false, otherwise (var accum 0.0)
evaluates to true." (loop [x :in xs] (*= accum x))
[& forms] accum)
(def len (length forms))
(if (= len 0)
false
((fn aux [i]
(def fi (get forms i))
(if
(>= (inc i) len) fi
(do
(if (atomic? fi)
(tuple 'if fi fi (aux (inc i)))
(do
(def $fi (gensym))
(tuple 'do (tuple 'def $fi fi)
(tuple 'if $fi $fi (aux (inc i))))))))) 0)))
(defmacro coro (defmacro coro
"A wrapper for making fibers. Same as (fiber (fn [] ...body))." "A wrapper for making fibers. Same as (fiber (fn [] ...body))."