1
0
mirror of https://github.com/janet-lang/janet synced 2024-11-24 17:27:18 +00:00

Add let macro.

This commit is contained in:
Calvin Rose 2018-03-11 16:30:38 -04:00
parent cace92af95
commit 807f9818a5
3 changed files with 22 additions and 2 deletions

View File

@ -704,7 +704,7 @@ DstAssembleResult dst_asm(Dst source, int flags) {
* NULL if not found. */
static const DstInstructionDef *dst_asm_reverse_lookup(uint32_t instr) {
size_t i;
uint32_t opcode = instr & 0xFF;
uint32_t opcode = instr & 0x7F;
for (i = 0; i < sizeof(dst_ops)/sizeof(DstInstructionDef); i++) {
const DstInstructionDef *def = dst_ops + i;
if (def->opcode == opcode)

View File

@ -90,7 +90,21 @@
(tuple 'def endsym end)
(tuple 'while (tuple '< sym endsym)
(tuple-prepend body 'do)
(tuple 'varset! sym (tuple '+ sym 1)))))
(tuple 'varset! sym (tuple '+ sym inc)))))
(defn even? [x] (== 0 (% x 2)))
(defn odd? [x] (== 1 (% x 2)))
(defmacro let [bindings & body]
(def head (ast-unwrap1 bindings))
(when (odd? (length head)) (error "expected even number of bindings to let"))
(var accum ['do])
(for [i 0 (length head) 2]
(array-push accum (tuple 'def
(get head i)
(get head (+ 1 i)))))
(array-push accum (tuple-prepend body 'do))
(apply tuple accum))
(defn pairs [x]
(var lastkey (next x nil))

View File

@ -259,6 +259,12 @@
(varset! count (+ 1 count)))
(assert (= (length syms) 128) "many symbols")))
# Let
(assert (= (let [a 1 b 2] (+ a b)) 3), "simple let")
(assert (= (let [[a b] [1 2]] (+ a b)) 3), "destructured let")
(assert (= (let [[a [c d] b] [1 (tuple 4 3) 2]] (+ a b c d)) 10), "double destructured let")
# Macros
(def defmacro macro (fn [name & more]