Common Lisp Cheat Sheet

Share
@,ecto
2 months ago
@ecto

Common Lisp Cheat Sheet

Basics

  • Comment:

    ; Is an inline comment, as part of a code line. It is almost never used.
    ;; Is a standard line comment.
    
  • Variable Declaration:

    (defvar var-name value)
    (setf var-name value)
    
  • Constant Declaration:

    (defconstant constant-name value)
    
  • Function Declaration:

    (defun function-name (args)
      body)
    

Conditionals

  • IF:

    (if condition
        then-clause
        else-clause)
    
  • COND:

    (cond
     (condition1 result1)
     (condition2 result2)
     ...
     (t default-result))
    
  • CASE:

    (case variable
      (value1 result1)
      (value2 result2)
      ...
      (t default-result))
    

Loops

  • DOLIST (for each item in a list):

    (dolist (var list result)
      body)
    
  • DOTIMES (repeat n times):

    (dotimes (var n result)
      body)
    
  • LOOP:

    (loop for var from start to end
          do body)
    

Lists

  • Creating a list:

    (list elem1 elem2 ...)
    
  • Car & Cdr:

    (car list)   ; Returns the first element
    (cdr list)   ; Returns the list excluding the first element
    

Note: When dealing with lists it's better to use first and rest than car and cdr. The latter should communicate dealing with conses as a data structure rather than conses as lists.

  • Append:
    (append list1 list2)
    

Strings

  • String concatenation:

    (concatenate 'string "Hello, " "world!")
    
  • String comparison:

    (string= str1 str2)
    

I/O

  • Print:

    (print expression)
    
  • Read:

    (read)
    
  • Format (similar to printf):

    (format nil "Hello, ~A" name)
    

Higher Order Functions

  • MAPCAR:

    (mapcar #'function-name list)
    
  • REDUCE:

    (reduce #'function-name list)
    
  • FILTER:

    (remove-if-not #'predicate list)
    

Error Handling

  • Condition Handling:
    (handler-case
        expression-to-try
      (error-type (variable)
        recovery-expression))