Skip to content

Lisp Syntax

Vishal Patil edited this page May 30, 2022 · 11 revisions

Syntax

Variables

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

If Expression

(if (> x 10) 1 2)
(if (!= x y) (sqr x) (cube y))

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)

Closures

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

(define add-5 (add-n 5))
(add-5 10)

Functional constructs

(map (lambda (x) (* x x)) (list 1 2 3 4 5))

(filter (lambda (x) (= 0 (% x 2))) (list 1 2 3 4 5))

(reduce (lambda (x y) (+ x y)) (list 1 2 3 4 5))
Clone this wiki locally