Skip to content

Instantly share code, notes, and snippets.

@shuaybi
shuaybi / intro1.clj
Created May 2, 2011 17:45
Intro to Clojure I
(+ 1 2 3)
(defn average [x y] (/ (+ x y) 2))
(map (addx 5) [1 2 3 4 5])
(map + [1 2 3] [4 5 6])
(map average [1 2 3] [4 5 6])
@shuaybi
shuaybi / graphics.clj
Created May 2, 2011 17:46
Intro Graphics
(defn xors [max-x max-y]
(for [x (range max-x) y (range max-y)]
[x y (bit-xor x y)]))
(xors 2 2)
(def frame (java.awt.Frame.))
(for [method (seq (.getMethods java.awt.Frame))
:let [method-name (.getName method)]
@shuaybi
shuaybi / dbc1.clj
Created May 2, 2011 17:48
Design By Contract 1
(defn pos-add [& args]
(apply + args))
(defn pos-add [& args]
{:pre [(not-any? neg? args)]
:post [(<= 0 %)]}
(apply + args))
(ns pas.perf)
(require 'pas.perf :reload)
;time and load perf data
(time (def p (load-perf-data)))
;show key
(.toString (first (keys p))
@shuaybi
shuaybi / trampoline1.clj
Created May 2, 2011 17:55
Trampoline I
(declare my-odd?)
(defn my-even? [n]
(if (zero? n)
true
(my-odd? (dec n))))
(defn my-odd? [n]
(if (zero? n)
false
@shuaybi
shuaybi / group.clj
Created May 2, 2011 21:14
Multi-level Grouping and Computations
(ns pas.tree
(:use [incanter core io charts datasets]))
(def reg-cntry-list
{"America" ["USA" "Canada" "Mexico" "Venezuala" "Brazil" "Argentina" "Cuba"]
"Asia" ["India" "Pakistan" "Singapore" "China" "Japan" "Sri Lanka" "Malaysia"]
"Europe" ["UK" "Germany" "France" "Italy" "Belgium" "Turkey" "Finland"]
"Middle East" ["Saudi Arabia" "Bahrain" "UAE" "Kuwait" "Yemen" "Qatar" "Iraq"]
"Africa" ["Libya" "Tanzania" "South Africa" "Kenya" "Ethiopia" "Morocco" "Zimbabwe"]})
@shuaybi
shuaybi / intro2.clj
Created May 5, 2011 14:54
Intro Clojure II
(defn fib [n]
(if (= n 0) 0
(if (= n 1) 1
(+ (fib (- n 1)) (fib (- n 2))))))
(defn lazy-seq-fibo
([]
(concat [0 1] (lazy-seq-fibo 0 1)))
([a b]
(let [n (+ a b)]
@shuaybi
shuaybi / rechier.clj
Created May 5, 2011 17:24
ExRecreateHier
(use '[clojure.contrib.map-utils
:only [deep-merge-with]])
(defn add-path [h path]
(let [dir (butlast path)
entry (last path)]
(update-in h dir (fn [x] (if x (conj x entry) [entry])))))
(defn restore-hierarchy [paths]
(reduce add-path {} paths))
;-------------------------
;clojure.core/merge-with
;([f & maps])
; Returns a map that consists of the rest of the maps conj-ed onto
; the first. If a key occurs in more than one map, the mapping(s)
; from the latter (left-to-right) will be combined with the mapping in
; the result by calling (f val-in-result val-in-latter).
; key/value pairs representing order-id and order-quantity
(def map1 {1 44 2 33})
-------------------------
;clojure.core/fnil
;([f x] [f x y] [f x y z])
; Takes a function f, and returns a function that calls f, replacing
; a nil first argument to f with the supplied value x. Higher arity
; versions can replace arguments in the second and third
; positions (y, z). Note that the function f can take any number of
; arguments, not just the one(s) being nil-patched.
(+ nil 1)