How do I do a conditional dispatch on a string in Common Lisp? I'm looking for something like:
(case str
("a" "found an a")
("abc" "found an abc")
(otherwise "other"))
so (case "a") returns "found an a"
Alexandria has the macros switch
, cswitch
, eswitch
:
(switch (str :test #'equal)
("a" "found an a")
("abc" "found an abc")
(t "other"))
The string-case library implements this functionality. It is available from quicklisp.
A trivial (and potentially slow) variant would be something like:
(defmacro string-case (str &rest forms)
(let* ((strval (gensym "STRVAL"))
(cond-body (loop for (s . f) in forms
collect `((string= ,strval ,s) ,@f))))
`(let ((,strval ,str)) (cond ,@cond-body))))
This (unfortunately) does not allow for an else
, otherwise
or grouping of strings, but making that extension should be pretty straight-forward. Using the existing string-case from quicklisp is probably the better choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With