Skip to content

Instantly share code, notes, and snippets.

@ato
ato / complex.clj
Created December 27, 2010 00:30
Stuart Sierra's automated 2-argument type dispatch with protocols
;; Quick fixup of http://paste.lisp.org/display/93387 for the final
;; datatypes/protocols syntax.
;;
;; With subtraction fixed.
(defn swap-args [f]
(fn [x y] (f y x)))
(defmacro defdouble
"Creates a function with 2-argument type dispatch."
(ns sliced-nio
"Just toying with NIO. Kinda dumb."
(:import (java.nio Buffer ByteBuffer)
(java.nio.channels FileChannel$MapMode)))
(defprotocol Slicable
(slice [this] [this ^long start ^long end]))
(defprotocol Decodable
(decode [this encoding]))
public class babench {
public static void microbench() {
byte[] ba = new byte[100000000];
long start = System.currentTimeMillis();
for (int i = 0; i < 80000000; i++) {
synchronized (ba) {
ba[i] = 0;
}
}
System.out.println("took " + (System.currentTimeMillis() - start) + " ms");
// Compiled with gcc -O
/*** Not locking ***/
#include <pthread.h>
#include <malloc.h>
int main() {
int i;
(defn microbench-lock []
(let [ba (byte-array 100000000)]
(time (dotimes [i 80000000] (locking ba (aset ba i (byte 0)))))))
(dotimes [j 10] (microbench-lock))
"Elapsed time: 9323.400529 msecs"
"Elapsed time: 9181.996864 msecs"
"Elapsed time: 9084.981462 msecs"
;; Clojure
(import 'java.io.ByteArrayOutputStream)
(defn microbench []
(let [baos (ByteArrayOutputStream. 100000000)]
(time (dotimes [i 80000000] (.write baos 0)))))
(dotimes [j 10] (microbench))
(def fib (memoize
(fn [n]
(if (<= n 1) 1
(+ (fib (dec n))
(fib (- n 2)))))) )
(time (fib 50))
;; "Elapsed time: 0.046096 msecs"
;; => 20365011074
(defun get-window-by-class (class)
"Return a window with the given class."
(first (filter-windows #'(lambda (w) (equal (window-class w) class)))))
(defun gimme (cmdline class)
"If a window matching CLASS is found switch to it, else launch cmdline."
(if class
(let ((wnd (get-window-by-class class)))
(if wnd
(display-window wnd)
(use 'clojure.contrib.def)
(defmacro foo [x] `'~x)
(defalias bar foo)
(foo blah) ;; -> blah
(bar blah) ;; -> blah
Clojure 1.1.0
user=> (use 'net.licenser.sandbox 'clojure.contrib.mock)
nil
user=> (def sb (new-sandbox-compiler))
#'user/sb
user=> ((sb '(let [myeval (atom nil)] (binding [meta #(reset! myeval %)] (clojure.contrib.mock/has-matching-signature? (read-string "eval") [])) @myeval)))
#'clojure.core/eval
user=> ((sb '(let [myeval (atom nil)] (binding [meta #(reset! myeval %)] (clojure.contrib.mock/has-matching-signature? (read-string "eval") [])) (@myeval (read-string "(def woohoo true)")))))
#'net.licenser.sandbox.box317/woohoo