Lisp Examples

Lisp syntax highlighting

Lisp Code Example

This is a general syntax for Lisp-like languages including Common Lisp, Scheme, Clojure, and others.

Basic Expressions

Example:

; Comments start with semicolon
;; Double semicolon for inline comments
;;; Triple semicolon for section headers

; Arithmetic
(+ 1 2)         ; => 3
(- 10 5)        ; => 5
(* 3 4)         ; => 12
(/ 20 4)        ; => 5

; Nested expressions
(+ (* 2 3) (- 5 1))  ; => 10

; Comparison
(= 5 5)         ; => #t
(< 3 5)         ; => #t
(> 10 2)        ; => #t
(<= 5 5)        ; => #t
(>= 10 5)       ; => #t

Variables and Definitions

Example:

; Define a variable (Scheme)
(define x 42)
(define pi 3.14159)
(define name "Alice")

; Set variable (Common Lisp)
(setq x 100)
(setq y 200)

; Let bindings - local variables
(let ((x 10)
      (y 20))
  (+ x y))  ; => 30

; Let* - sequential bindings
(let* ((x 5)
       (y (* x 2)))
  y)  ; => 10

Functions

Example:

; Define a function (Scheme)
(define (square x)
  (* x x))

(square 5)  ; => 25

; Define a function (Common Lisp)
(defun square (x)
  (* x x))

; Function with multiple parameters
(define (add x y)
  (+ x y))

(add 3 4)  ; => 7

; Recursive function
(define (factorial n)
  (if (<= n 1)
      1
      (* n (factorial (- n 1)))))

(factorial 5)  ; => 120

; Fibonacci
(define (fib n)
  (cond
    ((= n 0) 0)
    ((= n 1) 1)
    (else (+ (fib (- n 1))
             (fib (- n 2))))))

(fib 10)  ; => 55

Lambda Expressions

Example:

; Anonymous function
(lambda (x) (* x x))

; Using lambda directly
((lambda (x) (* x x)) 5)  ; => 25

; Lambda with multiple parameters
((lambda (x y) (+ x y)) 3 4)  ; => 7

; Assigning lambda to variable
(define square (lambda (x) (* x x)))

; Higher-order function
(define (apply-twice f x)
  (f (f x)))

(apply-twice (lambda (x) (* x 2)) 5)  ; => 20

Conditionals

Example:

; if expression
(if (> x 0)
    "positive"
    "not positive")

; Nested if
(if (< x 0)
    "negative"
    (if (> x 0)
        "positive"
        "zero"))

; cond - multiple conditions
(cond
  ((< x 0) "negative")
  ((> x 0) "positive")
  (else "zero"))

; when - single branch
(when (> x 0)
  (display "positive")
  (newline))

; unless
(unless (= x 0)
  (display "non-zero"))

Lists

Example:

; Empty list
'()
(list)

; List with elements
'(1 2 3 4 5)
(list 1 2 3 4 5)

; cons - construct list
(cons 1 '(2 3 4))  ; => (1 2 3 4)

; car - first element
(car '(1 2 3))  ; => 1

; cdr - rest of list
(cdr '(1 2 3))  ; => (2 3)

; List operations
(length '(1 2 3 4))     ; => 4
(append '(1 2) '(3 4))  ; => (1 2 3 4)
(reverse '(1 2 3))      ; => (3 2 1)

; nth element
(nth 0 '(a b c))  ; => a
(nth 2 '(a b c))  ; => c

Higher-Order Functions

Example:

; map - apply function to each element
(map (lambda (x) (* x 2)) '(1 2 3 4))
; => (2 4 6 8)

; filter - select elements matching predicate
(filter (lambda (x) (> x 5)) '(3 7 2 9 4 10))
; => (7 9 10)

; reduce/fold - combine elements
(reduce + '(1 2 3 4 5))  ; => 15

; Apply function to list of arguments
(apply + '(1 2 3 4))  ; => 10

Quoted Expressions

Example:

; Quote - prevent evaluation
'x              ; => x (symbol)
'(1 2 3)        ; => (1 2 3) (list)
'(+ 1 2)        ; => (+ 1 2) (not 3)

; quote function
(quote x)
(quote (1 2 3))

; Backquote and unquote
`(1 2 ,(+ 1 2))  ; => (1 2 3)
`(a b ,x)        ; => (a b 42) if x=42

; Unquote-splicing
`(1 ,@(list 2 3) 4)  ; => (1 2 3 4)

Strings

Example:

; String literals
"Hello, World!"
"Multi-line
string"

; String concatenation
(string-append "Hello" " " "World")  ; => "Hello World"

; String length
(string-length "Hello")  ; => 5

; Substring
(substring "Hello World" 0 5)  ; => "Hello"

; String comparison
(string=? "abc" "abc")  ; => #t
(string #t

; Escape sequences
"Say \"Hello\""
"Line 1\nLine 2"
"Tab\there"

Numbers

Example:

; Integers
42
-17
0

; Floating point
3.14
-2.5
1.0e10

; Hexadecimal
0xFF
0x1A2B

; Fractions (Scheme)
1/2
3/4

; Complex numbers (Scheme)
3+4i

; Number predicates
(number? 42)    ; => #t
(integer? 3.5)  ; => #f
(even? 4)       ; => #t
(odd? 5)        ; => #t
(zero? 0)       ; => #t
(positive? 5)   ; => #t
(negative? -3)  ; => #t

Boolean and Logic

Example:

; Boolean values
#t  ; true
#f  ; false

; Logical operations
(and #t #t)      ; => #t
(and #t #f)      ; => #f
(or #f #t)       ; => #t
(or #f #f)       ; => #f
(not #t)         ; => #f
(not #f)         ; => #t

; Short-circuit evaluation
(and (> x 0) (< x 10))
(or (= x 0) (= x 1))

Type Predicates

Example:

; Check types
(number? 42)       ; => #t
(string? "hello")  ; => #t
(symbol? 'x)       ; => #t
(list? '(1 2 3))   ; => #t
(pair? '(1 . 2))   ; => #t
(null? '())        ; => #t
(boolean? #t)      ; => #t
(procedure? +)     ; => #t

Associations and Hash Tables

Example:

; Association lists
(define alist '((name . "Alice") (age . 30)))

(assoc 'name alist)   ; => (name . "Alice")
(cdr (assoc 'age alist))  ; => 30

; Add association
(cons '(city . "NYC") alist)

; Hash tables (Common Lisp)
(setq ht (make-hash-table))
(setf (gethash 'name ht) "Alice")
(setf (gethash 'age ht) 30)
(gethash 'name ht)  ; => "Alice"

Loops and Iteration

Example:

; Recursive loop
(define (sum-list lst)
  (if (null? lst)
      0
      (+ (car lst) (sum-list (cdr lst)))))

; Named let (Scheme)
(let loop ((i 0) (sum 0))
  (if (< i 10)
      (loop (+ i 1) (+ sum i))
      sum))

; dolist (Common Lisp)
(dolist (x '(1 2 3 4))
  (print (* x x)))

; dotimes (Common Lisp)
(dotimes (i 10)
  (print i))

; do loop (Scheme)
(do ((i 0 (+ i 1))
     (sum 0 (+ sum i)))
    ((>= i 10) sum))

Macros (Advanced)

Example:

; Simple macro (Scheme)
(define-syntax when
  (syntax-rules ()
    ((when test body ...)
     (if test
         (begin body ...)))))

; Using the macro
(when (> x 0)
  (display "positive")
  (newline))

; Macro with pattern matching
(define-syntax for
  (syntax-rules (in)
    ((for var in list body ...)
     (map (lambda (var) body ...) list))))

; defmacro (Common Lisp)
(defmacro when (test &rest body)
  `(if ,test
       (progn ,@body)))

Advanced Examples

Example:

; Quicksort
(define (quicksort lst)
  (if (null? lst)
      '()
      (let ((pivot (car lst))
            (rest (cdr lst)))
        (append
          (quicksort (filter (lambda (x) (< x pivot)) rest))
          (list pivot)
          (quicksort (filter (lambda (x) (>= x pivot)) rest))))))

(quicksort '(3 1 4 1 5 9 2 6))  ; => (1 1 2 3 4 5 6 9)

; Map-reduce pattern
(define (map-reduce map-fn reduce-fn init lst)
  (reduce reduce-fn
          init
          (map map-fn lst)))

; Binary tree operations
(define (make-tree value left right)
  (list value left right))

(define (tree-value tree) (car tree))
(define (tree-left tree) (cadr tree))
(define (tree-right tree) (caddr tree))

(define (tree-insert tree value)
  (if (null? tree)
      (make-tree value '() '())
      (let ((root (tree-value tree)))
        (cond
          ((< value root)
           (make-tree root
                      (tree-insert (tree-left tree) value)
                      (tree-right tree)))
          ((> value root)
           (make-tree root
                      (tree-left tree)
                      (tree-insert (tree-right tree) value)))
          (else tree)))))

; Y-combinator (fixed-point combinator)
(define Y
  (lambda (f)
    ((lambda (x) (f (lambda (y) ((x x) y))))
     (lambda (x) (f (lambda (y) ((x x) y)))))))

; Factorial using Y-combinator
((Y (lambda (fact)
      (lambda (n)
        (if (<= n 1)
            1
            (* n (fact (- n 1)))))))
 5)  ; => 120