1
0
mirror of https://github.com/janet-lang/janet synced 2025-02-03 02:39:09 +00:00

Merge pull request #1190 from primo-ppcg/if-let

update if-let
This commit is contained in:
Calvin Rose 2023-06-18 09:38:44 -05:00 committed by GitHub
commit cfffc0bcf1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 3 deletions

View File

@ -668,14 +668,20 @@
(def len (length bindings))
(if (= 0 len) (error "expected at least 1 binding"))
(if (odd? len) (error "expected an even number of bindings"))
(def res (gensym))
(defn aux [i]
(if (>= i len)
tru
~(do (set ,res ,tru) true)
(do
(def bl (in bindings i))
(def br (in bindings (+ 1 i)))
(tuple 'if (tuple 'def bl br) (aux (+ 2 i)) fal))))
(aux 0))
(if (symbol? bl)
~(if (def ,bl ,br) ,(aux (+ 2 i)))
~(if (def ,(def sym (gensym)) ,br)
(do (def ,bl ,sym) ,(aux (+ 2 i))))))))
~(do
(var ,res nil)
(if ,(aux 0) ,res ,fal)))
(defmacro when-let
"Same as `(if-let bindings (do ;body))`."

View File

@ -129,6 +129,13 @@
(assert (= (if-let [a my-array k (next a 5)] :t :f) :f) "if-let 4")
(assert (= (if-let [[a b] my-array] a) 1) "if-let 5")
(assert (= (if-let [{:a a :b b} {:a 1 :b 2}] b) 2) "if-let 6")
(assert (= (if-let [[a b] nil] :t :f) :f) "if-let 7")
# #1191
(var cnt 0)
(defmacro upcnt [] (++ cnt))
(assert (= (if-let [a true b true c true] nil (upcnt)) nil) "issue #1191")
(assert (= cnt 1) "issue #1191")
(assert (= 14 (sum (map inc @[1 2 3 4]))) "sum map")
(def myfun (juxt + - * /))