Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions Switch.ark
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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) })
21 changes: 20 additions & 1 deletion tests/switch-tests.ark
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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)) })
Loading