Skip to content

Instantly share code, notes, and snippets.

View Clojure Syntax 1.clj
; Syntax
(if (= 0 0) "a" "b") ;"a"
(do (print "a" "b")) ;a"b"
(when true "a") ;"a"
(def a "a") ;"a"
(def b ["a" "b"]) ;["a" "b"]
;Data Structures
(nil? 1) ;false
(nil? nil) ;true
View SICP 2.39
(define (reverse sequence)
(fold-right (lambda (x y) (cons y x)) null sequence))
(define (reverse2 sequence)
(fold-left (lambda (x y) (cons y x)) null sequence))
View SICP 2.37
(define (dot-product v w)
(accumulate + 0 (map * v w)))
(define (matrix-*-vector m v)
(map (lambda (row) (dot-product row v))
m))
(define (transpose mat)
(accumulate-n cons null mat))
View SICP 2.36
(define (accumulate-n op init seqs)
(if (null? (car seqs))
null
(cons (accumulate op init (map car seqs))
(accumulate-n op init (map cdr seqs)))))
View SICP 2.35
;; Flatten tree then count
(define (count-leaves0 t)
(accumulate (lambda (x total) (+ total 1)) 0
(map (lambda (children) children)
(enumerate-tree t))))
(define (count-leaves1 t)
(accumulate + 0
(map (lambda (children)
View SICP 2.34
(define (horner-eval x coefficient-sequence)
(accumulate (lambda (this-coeff higher-terms) (+ this-coeff (* higher-terms x)))
0
coefficient-sequence))
View SICP 2.33
(define (map proc sequence)
(accumulate (lambda (x y) (cons (proc x) y)) null sequence))
(define (append seq1 seq2)
(accumulate cons seq2 seq1))
(define (length sequence)
(accumulate (lambda (x y) (+ y 1)) 0 sequence))
View SICP 2.32
(define (subsets s)
(if (null? s)
(list null)
(let ((rest (subsets (cdr s))))
(append rest ;;; append is like + for list
(map (lambda (l) (cons (car s) l)) rest)))))
View SICP 2.31
(define (tree-map proc root)
(map (lambda (children)
(cond ((null? children) null)
((pair? children) (tree-map proc children))
(else (proc children))))
root))
(define (square-tree tree) (tree-map square tree))
View SICP 2.30.part3
(define (square-tree2 tree)
(if (pair? tree)
(map square-tree2 tree)
(* tree tree)))