Skip to content

Instantly share code, notes, and snippets.

@michalmarczyk
michalmarczyk / type-fun.clj
Created April 24, 2010 05:14
fooling around with Clojure interfaces, part 1
(deftype Foo [x y z]
clojure.lang.IKeywordLookup
(getLookupThunk
[self k]
(reify
clojure.lang.ILookupThunk
(get
[self k]
(if-let [v (k {:x x :y y :z z})]
(inc v)))))
@michalmarczyk
michalmarczyk / pv-structure-sharing.clj
Created April 25, 2010 22:31
demonstrating structural sharing in clojure.lang.PersistentVector instances
;; demonstrating structural sharing
;; in clojure.lang.PersistentVector
;; instances
(let [v1 (vec (range 100))
v2 (conj v1 :foo)
v3 (conj v1 :bar)
v4 (conj (vec (range 100)) :quux)
PV-root (doto (.getDeclaredField clojure.lang.PersistentVector "root")
(.setAccessible true))
(ns prolog
(:use clojure.contrib.def
clojure.contrib.str-utils
clojure.set
clojure.test))
(defvar facts (ref {:forward {} :back {}}) "Hashmap of clauses (forward and back references)")
(defn passmap
"Applies f to items only when (pred item) returns true."
(ns hiredman.beans)
(defn -it [& _]
[[] (ref {})])
(defn setter [tis nam tat]
(dosync
(commute (.state tis)
assoc nam tat)))
; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(set! *warn-on-reflection* true)
package mypkg;
public class Ugly {
public Ugly(){}
public String foo(boolean i) { return "bool: " + i; }
public String foo(Object o) { return "obj: " + o; }
}
user> (def u (foo.TestInterop2.))
#'user/u
(use '[clojure.contrib.macro-utils :only [macrolet]])
(defmacro defplugin [& body]
(let [g (gensym)]
(macrolet [(defcommand [docs words cmdkey & method-stuff]
`(do (dosync (doseq [word# ~words]
(assoc ~g word# {:cmd ~cmdkey :doc ~docs})))
(defmethod respond ~cmdkey ~@method-stuff)))]
`(let [~g (ref [])]
~@body
@michalmarczyk
michalmarczyk / defmap.clj
Created April 28, 2010 09:11
macrolet example
(defmacro defmap [name & body]
(let [g (gensym)]
`(macrolet [(~'add [k# v#] `(swap! ~'~g assoc ~k# ~v#))]
(let [~g (atom {})]
~@body
(def ~name (deref ~g))))))
(deftype SuperLazySeq [f r]
clojure.lang.ISeq
(first [self] (force f))
(next [self] r)
clojure.lang.Seqable
(seq [self] self))
(defmacro sl-cons [x sls]
`(SuperLazySeq. (delay ~x) ~sls))
(set! *warn-on-reflection* true)
(import (org.mozilla.javascript Context NativeObject NativeArray))
(defn js-eval [string]
(let [cx (Context/enter)
scope (.initStandardObjects cx)]
(.evaluateString cx scope string "<js-eval>" 1 nil)))
(defprotocol Clojurify (clojurify [obj]))