Skip to content

Lisp Syntax

Vishal Patil edited this page Dec 31, 2024 · 11 revisions

Syntax

Variables

(define x 1)
(define y 1.0)
(define city "Chapel Hill")
(define cities (list "Raleigh" "Durham" "Chapel Hill"))

Let

(let ((x 2) (y 3))
       (let ((x 7)
          (z (+ x y)))
            (* z x))) 

Begin

(begin
   (define (double value) 
      (* 2 value))
   (define (apply-twice fn value) 
      (fn (fn value)))
        
   (apply-twice double 5)
)

If Expression

(if (> x 10) 1 2)
(if (!= x y) (sqr x) (cube y))
(if #t 3 4)
(if #f (sqr 3) (cube 4))

Lambda Expression

(define sum 
   (lambda (x y) (+ x y)))

(sum 10 20.0)

(define sqr 
   (lambda (x) (* x x)))
(sqr 20)

(define area-of-circle 
   (lambda (r) (* pi (sqr r))))

(area-of-circle 10.0)

(define is-even 
   (lambda (x) (= 0 (% x 2))))

(is-even 10)

Functions

(define pi 3.14)
(define (area-of-circle r) 
          (* pi (* r r)))

Closures

(define add-n 
   (lambda (n) 
      (lambda (a) (+ n a))))

(define add-5 (add-n 5))
(add-5 10)
Clone this wiki locally