Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 836
Sagar0921 Avatar asked Nov 30 '22 16:11

Sagar0921


2 Answers

You can use the library alexandria, which has a configurable switch macro:

(switch ("XY" :test 'equal)
  ("XY" "an X and a Y")
  ("AB" "an A and a B"))
like image 110
Svante Avatar answered Jan 22 '23 08:01

Svante


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.

like image 40
Sylwester Avatar answered Jan 22 '23 06:01

Sylwester