Skip to content

Instantly share code, notes, and snippets.

@nathanmarz
nathanmarz / gist:7fb2ef8af5c2293b56ee
Created June 27, 2014 05:49
clojure monad parser
(use 'clojure.algo.monads)
(def parser-m (state-t maybe-m))
(defmacro parserfn [& body]
`(domonad parser-m ~@body))
(with-monad parser-m
(defn optional [p] (m-plus p (m-result nil)))
@nathanmarz
nathanmarz / gist:6333a50c67ec9031e5ee
Last active August 29, 2015 14:23
New if-path selector in Specter
;; For every map, if value for :a is even, increment :b's value. Otherwise, increment all values.
(update [ALL (if-path [:a even?] :b [ALL LAST])]
inc
[{:a 2 :b 3 :c 4}
{:a 1 :b 10 :d 5 :e 6}
{:a 2 :b 0}
{:a -1 :f 100}])
==>
[{:c 4, :b 4, :a 2}
@nathanmarz
nathanmarz / gist:7a6bbf80770d2a232f33
Created June 24, 2015 17:11
Practical example of Specter
(def world
{:people [{:money 129827 :name "Alice Brown"}
{:money 100 :name "John Smith"}
{:money 6821212339 :name "Donald Trump"}
{:money 2870 :name "Charlie Johnson"}
{:money 8273821 :name "Charlie Rose"}
]
:bank {:funds 4782328748273}}
)
@nathanmarz
nathanmarz / protocol-metadata-test-case.clj
Created August 8, 2015 14:02
Protocol functions and metadata do not play well together
(defprotocol TestProtocol
(tester [o]))
(def tester-with-meta (with-meta tester {:a 1}))
(extend-protocol TestProtocol
String
(tester [o] (println "Strings work!")))
(tester-with-meta "A") ;; Error
@nathanmarz
nathanmarz / protocol-function-failures.clj
Created August 8, 2015 15:50
Protocol functions fail to find extensions is assigned to locals or other var
(defprotocol TestProtocol
(tester [o]))
(let [t tester]
(defn another-tester [o]
(t o)))
(def another-tester2 tester)
(extend-protocol TestProtocol
(w/defbufferop sum-stats [tuples]
[(rest (reduce (fn [[id-old & vals-old :as old] [id & vals]]
(if (= id-old id)
old
(cons id (map + vals-old vals))))
tuples))]))
@nathanmarz
nathanmarz / gist:511938
Created August 6, 2010 20:20
Random number in Cascalog
import cascading.flow.FlowProcess;
import cascading.flow.hadoop.HadoopFlowProcess;
import cascading.operation.FunctionCall;
import cascading.operation.OperationCall;
import cascading.tuple.Tuple;
import java.util.Random;
import cascalog.CascalogFunction;
public class RandInt extends CascalogFunction {
long _seed;
;; Source:
(defmacro binder [& body]
(let [[tobind lexpr] (split-at (dec (count body)) body)
binded (vec (mapcat (fn [e]
(if (and (list? e) (= 'bind (first e)))
[(second e) (last e)]
['_ e]
))
tobind ))]
`(let ~binded
(def average
(<- [!val :> !avg])
(c/count !count)
(c/sum !val :> !sum)
(div !sum !count :> !avg))
(-invoke [this p01 p02 p03 p04 p05 p06 p07 p08 p09 p10
p11 p12 p13 p14 p15 p16 p17 p18 p19 p20
rest]
(let [a (object-array
(concat
[p01 p02 p03 p04 p05 p06 p07 p08 p09 p10
p11 p12 p13 p14 p15 p16 p17 p18 p19 p20]
rest))]
(com.rpl.specter.impl/bind-params* this a 0))
)