Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Switch in Common Lisp

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"

like image 934
Jeff Linahan Avatar asked Sep 16 '15 05:09

Jeff Linahan


3 Answers

Alexandria has the macros switch, cswitch, eswitch:

(switch (str :test #'equal)
  ("a" "found an a")
  ("abc" "found an abc")
  (t "other"))
like image 108
Svante Avatar answered Nov 13 '22 04:11

Svante


The string-case library implements this functionality. It is available from quicklisp.

like image 38
PuercoPop Avatar answered Nov 13 '22 03:11

PuercoPop


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.

like image 2
Vatine Avatar answered Nov 13 '22 03:11

Vatine