Skip to content

Instantly share code, notes, and snippets.

View timmc's full-sized avatar

Tim McCormack timmc

View GitHub Profile
(defmacro def+keep-meta [name a-var]
`(alter-meta! (def ~name ~a-var) merge (meta ~a-var)))
@timmc
timmc / core.clj
Created March 23, 2012 15:04
Profiling ints vs floats
(ns clj.core
(:use [criterium.core :only (bench with-progress-reporting)]))
(defmacro accumulate
"Captures symbol 'acc as accumulator."
[init-e next-e]
`(loop [c# (int 1e8)
~'acc ~init-e]
(if (zero? c#)
~'acc
@timmc
timmc / core.clj
Created April 7, 2012 22:49
Return type hinting, imports, and namespace boundaries
(ns clj.core
"Relying namespace."
(:require [clj.util :as u]))
(defn config-dir
"Call "
[conf]
(.getCanonicalFile (u/make-file)))
(import '(java.io ByteArrayInputStream ByteArrayOutputStream
ObjectInputStream ObjectOutputStream))
(defmacro wtf
[]
(Boolean. false)) ;; note the lack of syntax-quote
---------
user=> (wtf)
@timmc
timmc / gist:3036114
Created July 2, 2012 22:22
Factorial in Clojure without using alphanumeric characters
(#(% [% (+ (*)(*)(*)(*)(*)(*)(*))])
#(if (= (% (*)) (+))
(*)
(* ((% (+))
[(% (+)) (- (% (*)) (*))])
(% (*)))))
;; => 5040
;; Almost there, just an "if" to get rid of...
(#((% (+(*))) %) ;; call arg 1 with all args
@timmc
timmc / fact.swear.clj
Last active July 5, 2022 13:34
Factorial in Clojure without using alphanumeric characters
;; It all started here: http://clojure-log.n01se.net/date/2011-04-06.html#19:04
(#((% (+(*))) %) ;; call arg 1 with all args
[;; data
(+ (*)(*)(*)(*)(*)(*)(*))
;; main fn -- simulate 'if' with map lookup and closures
#(({(+) (% (+(*)(*)))} ;; if zero return 'then' clause
(% (+)) ;; dispatch on first arg
(% (+(*)(*)(*)))) ;; call 'else' clause (n not found in map)
%)
@timmc
timmc / gist:3218623
Created July 31, 2012 17:13
variant on swap! that returns the old value
(defn swap2! [a f & args]
(let [oldp (promise)
f* (fn [oldv] (deliver oldp oldv) (apply f oldv args))]
(swap! a f*) @oldp))
@timmc
timmc / snippet.clj
Created September 29, 2012 16:17
Swing threads
(defn make-human-move
"Block until human has moved, then return move."
[g]
(SwingUtilities/invokeLater #(update-ui-game-state g human-player-id))
(reset! human-turn? true)
;; Block until human has moved
(.take human-moves))
@timmc
timmc / fib.clj
Created October 9, 2012 21:53 — forked from thiagofm/fib.clj
fib clojure
;; Changes:
;; - use + instead of reduce +
;; - only calculate (+ actual-n next-n) once per iteration
;; - No dangling closing parens
;; - dec instead of (- ... 1) (to taste)
;; - zero? instead of (= ... 0)
;; - reverse the if clauses to take care of the base case first
(defn fib-list
[actual-n next-n iterations-left full-list]
@timmc
timmc / fib2.clj
Created October 9, 2012 22:43 — forked from thiagofm/fib2.clj
fib clojure 2
(defn fib
([n]
(fib [0 1] (- n 2)))
([list-fib n]
(if (zero? n)
list-fib
(recur (conj list-fib (apply + (take-last 2 list-fib)))
(dec n)))))
(fib 10)