Search code examples
switch-statementlispcommon-lisp

Switch statement in Lisp


Switch statement with Strings in Lisp.

    (defun switch(value) 
      (case value
        (("XY") (print "XY"))
        (("AB") (print "AB"))
      )
    ) 

I want to compare if value is "XY" then print "XY" or same for "AB". I have tried this code but it gives me nil. Can some please tell me what i am doing wrong?


Solution

  • print("XY") looks more like Algol (and all of its descendants) rather than LISP. To apply print one would surround the operator and arguments in parentheses like (print "XY")

    case happens to be a macro and you can test the result yourself with passing the quoted code to macroexpand and in my implementation I get:

    (let ((value value)) 
      (cond ((eql value '"XY") (print "XY")) 
            ((eql value '"AB") (print "AB"))))
    

    You should know that eql is only good for primiitive data types and numbers. Strings are sequences and thus (eql "XY" "XY") ;==> nil

    Perhaps you should use something else than case. eg. use cond or if with equal.