diff --git a/Switch.ark b/Switch.ark index 550e8e8..ad88f26 100644 --- a/Switch.ark +++ b/Switch.ark @@ -1,3 +1,10 @@ +(macro _switch_impl (var case then ...cases) { + ($if (= "_" ($repr case)) + then + (if (= var case) + then + ($if (>= ($len cases) 2) (_switch_impl var ...cases)))) }) + # @brief Takes a value to match against a list of (possible value, code to run)... # @param value value to match # @param case first case @@ -14,8 +21,6 @@ # =end # @author https://github.com/SuperFola (macro switch (value case then ...cases) { - ($if (= "_" ($repr case)) - then - (if (= value case) - then - ($if (>= ($len cases) 2) (switch value ...cases)))) }) + (macro var ($gensym)) + (let var value) + (_switch_impl var case then ...cases) }) diff --git a/tests/switch-tests.ark b/tests/switch-tests.ark index 665af27..4308fb4 100644 --- a/tests/switch-tests.ark +++ b/tests/switch-tests.ark @@ -1,6 +1,14 @@ (import std.Switch) (import std.Testing) +(mut called 0) +(let foo (fun () { + (set called (+ 1 called)) + (if (> 1 called) + (test:expect false "foo shouldn't be evaluated more than once") + (test:expect true)) + called })) + (test:suite switch { (switch 12 0 (test:expect false) @@ -17,4 +25,15 @@ (switch 1 1 (test:expect true)) (switch 1 - 2 (test:expect false)) }) + 2 (test:expect false)) + + (switch (foo) + 0 (test:expect false) + 1 (test:expect true) + 2 (test:expect false) + _ (test:expect false)) + + (switch (let n 1) + 0 (test:expect false) + 1 (test:expect true) + _ (test:expect false)) })