Shammer's Philosophy

My private adversaria

Using typecase in Common Lisp

I wrote some functions that need to check the type of valuable with using cond with numberp, stringp, characterp etc, here is a sample.

(cond ((numberp x)
            ; do something here
             ...)
           ((stringp x)
            ; do something here
             ...)
           (t 
             ...))

But, there is a function(might be macro) named typecase. This enables judging valuable type more smart sentense. These are my samples to use typecase.

(defun int (x)
  (typecase x
    (number x)
    (string (parse-integer x :junk-allowed t))
    (character (int (string x)))
    (t nil)))

(defun str (x)
  (typecase x
    (cons (concatenate 'string (str (car x)) (str (cdr x))))
    (string x)
    (number (write-to-string x))
    (character (string x))
    (t "")))