Skip to content

Instantly share code, notes, and snippets.

View fogus's full-sized avatar
💭
attempting to learn how to better learn

Fogus fogus

💭
attempting to learn how to better learn
View GitHub Profile
(defconstrainedfn sqr
"Squares a number"
[n]
:requires
number?
(not= 0 n)
:ensures
pos? number?
(def constrained-sqr
(with-constraints
sqr
sqr-contract))
(constrained-sqr 5)
;=> 25
(constrained-sqr -5)
;=> 25
(use [fogus.me.trammel :only [apply-contracts]])
(defn sqr [n]
(* n n))
(apply-contracts
[sqr [n] :requires number? (not= 0 n)
:ensures pos? number?])
(ns a)
(defn ^{:private true} foo [] 42)
(ns b)
(a/foo)
; explosion
(def n (find-ns 'a))
(((ns-map n) 'foo))
;=> 42
;; stolen from http://cemerick.com/2010/08/02/defrecord-slot-defaults/
(defmacro defrecord+defaults
"Defines a new record, along with a new-RecordName factory function that
returns an instance of the record initialized with the default values
provided as part of the record's slot declarations. e.g.
(defrecord+ Foo [a 5 b \"hi\"])
(new-Foo)
=> #user.Foo{:a 5, :b \"hi\"}"
[name slots & etc]
; STM history stress-test
(defn stress [hmin hmax]
(let [r (ref 0 :min-history hmin :max-history hmax)
slow-tries (atom 0)]
(future
(dosync
(swap! slow-tries inc)
(Thread/sleep 200)
@r)
(defn plot [f min max step]
(doseq [i (range min max step)]
(dotimes [_ (apply f [i])] (print "*"))
(println)))
(plot #(Math/pow % 2) 1 5 1)
; *
; ****
(defmulti repeating-mm (juxt first second))
(defmethod repeating-mm [1 2] [_] (str [1 2]))
(repeating-mm (range 1 10))
;=> "[1 2]"
(defmacro defmethod-anaphoric
[multifn dispatch-val & fn-tail]
`(. ~(with-meta multifn {:tag 'clojure.lang.MultiFn})
addMethod
(let [example (fn [a & {:keys [b c]}] [a b c])]
[(example 1)
(example 1 :b 42)
(example 1 :b 42 :c 108)])
;=> [[1 nil nil] [1 42 nil] [1 42 108]]
@fogus
fogus / core.clj
Created August 16, 2010 18:13 — forked from hiredman/core.clj
(defmacro fork [x & bodies]
(let [n (gensym)]
`(let [~n ~x]
(pvalues
~@(map (fn [[a & b]]
(cons a (cons n b)))
bodies)))))
(defn join [results fn]
(fn results))