diff --git a/projects/advent-of-code/src/year2020/Solutions.kiss b/projects/advent-of-code/src/year2020/Solutions.kiss index 75b08cc1..c4e4f205 100644 --- a/projects/advent-of-code/src/year2020/Solutions.kiss +++ b/projects/advent-of-code/src/year2020/Solutions.kiss @@ -30,9 +30,8 @@ (deflocal :Map numbersMap (new Map)) (deflocal &mut pair null) (doFor number numbers - // TODO implement dict-set, dict-get, set-nth, and use them - (set (nth numbersMap number) (- sum number)) - (let [requiredForPair (nth numbersMap number)] + (dict-set numbersMap number (- sum number)) + (let [requiredForPair (dict-get numbersMap number)] (when (numbersMap.exists requiredForPair) (set pair (or pair [number requiredForPair]))))) diff --git a/src/kiss/Macros.hx b/src/kiss/Macros.hx index 13abe2de..80dab6ee 100644 --- a/src/kiss/Macros.hx +++ b/src/kiss/Macros.hx @@ -100,6 +100,21 @@ class Macros { ]).withPosOf(wholeExp); }; + function arraySet(wholeExp:ReaderExp, exps:Array, k:KissState) { + return CallExp(Symbol("set").withPosOf(wholeExp), [ + CallExp(Symbol("nth").withPosOf(wholeExp), [exps[0], exps[1]]).withPosOf(wholeExp), + exps[2] + ]).withPosOf(wholeExp); + } + macros["set-nth"] = (wholeExp:ReaderExp, exps:Array, k:KissState) -> { + wholeExp.checkNumArgs(3, 3, "(set-nth [list] [index] [value])"); + arraySet(wholeExp, exps, k); + }; + macros["dict-set"] = (wholeExp:ReaderExp, exps:Array, k:KissState) -> { + wholeExp.checkNumArgs(3, 3, "(dict-set [dict] [key] [value])"); + arraySet(wholeExp, exps, k); + }; + // Under the hood, (defmacrofun ...) defines a runtime function that accepts Quote arguments and a special form that quotes the arguments to macrofun calls macros["defmacrofun"] = (wholeExp:ReaderExp, exps:Array, k:KissState) -> { wholeExp.checkNumArgs(3, null, "(defmacrofun [name] [args] [body...])"); diff --git a/src/kiss/SpecialForms.hx b/src/kiss/SpecialForms.hx index d78fe557..155f4a01 100644 --- a/src/kiss/SpecialForms.hx +++ b/src/kiss/SpecialForms.hx @@ -25,9 +25,16 @@ class SpecialForms { EBlock([for (bodyExp in args) k.convert(bodyExp)]).withMacroPosOf(wholeExp); }; + function arrayAccess(wholeExp:ReaderExp, args:Array, k:KissState) { + return EArray(k.convert(args[0]), k.convert(args[1])).withMacroPosOf(wholeExp); + }; map["nth"] = (wholeExp:ReaderExp, args:Array, k:KissState) -> { wholeExp.checkNumArgs(2, 2, "(nth [list] [idx])"); - EArray(k.convert(args[0]), k.convert(args[1])).withMacroPosOf(wholeExp); + arrayAccess(wholeExp, args, k); + }; + map["dict-get"] = (wholeExp:ReaderExp, args:Array, k:KissState) -> { + wholeExp.checkNumArgs(2, 2, "(dict-get [dict] [key])"); + arrayAccess(wholeExp, args, k); }; function makeQuickNth(idx:Int, name:String) {