Skip to content

Instantly share code, notes, and snippets.

@kouddy
kouddy / Clojure Syntax 1.clj
Last active September 17, 2015 00:53
Clojure Syntax
; 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
(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))
(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))
(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)))))
;; 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)
(define (horner-eval x coefficient-sequence)
(accumulate (lambda (this-coeff higher-terms) (+ this-coeff (* higher-terms x)))
0
coefficient-sequence))
(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))
(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)))))
(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))
(define (square-tree2 tree)
(if (pair? tree)
(map square-tree2 tree)
(* tree tree)))