case with two alternative options per command #1417
-
I would like to reproduce this POSIX shell code with two alternative options per match/command: case "$1" in
-h|--help) usage; exit ;;
-V|--version) echo "$VERSION"; exit ;;
esac The verbose way would be something like: (case arg
case1a command1
case1b command1
case2a command2
case2b command2) I have tried to create a macro that turns My attempt: (defmacro twocases [case1 case2 command]
case1 command case2 command) It does not work: (case 3
(twocases 1 2 (print "1 or 2"))
(twocases 3 4 (print "3 or 4"))) This prints Can macros return multiple symbols at all? Or only one form? Could somebody tell me why this doesn't work? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Yeah, Janet's native macros can only expand to a single form, so there's not a direct way to do what you're trying to do.
(def subject 3)
(cond
(or (= subject 1) (= subject 2)) (print "one or two")
(or (= subject 3) (= subject 4)) (print "three or four")) But that's clearly not as nice as I've written a library called (import pat)
(pat/match 3
(or (= 1) (= 2)) (print "one or two")
(or (= 3) (= 4)) (print "three or four"))
# or even more succinctly:
(pat/match 3
(or ,1 ,2) (print "one or two")
(or ,3 ,4) (print "three or four"))
Also if you are literally trying to replicate that argument-parsing code, you might consider (cmd/def
--other-flag :string
[-v --version] (effect (fn []
(print "1.0")
(os/exit 0))))
(print other-flag) And will automatically generate |
Beta Was this translation helpful? Give feedback.
Yeah, Janet's native macros can only expand to a single form, so there's not a direct way to do what you're trying to do.
case
is a special-case ofcond
, and you could usecond
directly:But that's clearly not as nice as
case
. It would be possible to write a customcase
macro that understood yourtwocases
form, but it's kinda sad that it wouldn't compose with built-in things. There are... ways... to define macros that would allow your generaltwocases
macro to work. But... that's not really accessible.I've written a library called
pat
that has amatch
…