Code Snippets Clojure

Short texts Clojure 🧑‍💻 Code snippets Clojure ✍️ Reading lists Clojure 👀

moving-average-lazy.clj

(defn- lazy-reduce [f init acc] (lazy-seq (if (seq acc) (lazy-reduce f (f init (first acc)) (rest acc)) init))) (defn moving-average-lazy [values period] (loop [values values, period period, acc []] (let [first (take period values)] (if (= (count first) period) (recur (rest values) period (lazy-seq (cons (/ (reduce + first) period) acc))) (lazy-reduce conj () acc))))) […]

Macro to create a decorator (wrapper) for a objects implementing a Java interface

;; A macro to create a decorator (wrapper) for a objects implementing a Java interface ;; Disclaimer: The code most certainly is not perfect and does not handle some corner cases ;; License: The Unlicense http://unlicense.org/ (require ‘[clojure.string :as str]) (defn type->tag [parameter-type] (let [array? (-> parameter-type name (str/ends-with? “”)) primitive? ‘#{int long float double […]

stress terminus 2 threads

(do :stresstest (require ‘clj-http.client) (def DURATION 10) (def tics (atom 1)) (def responses (atom [])) (def start (System/currentTimeMillis)) (defn rand-query [] {“@type” “woql:AddTriple”, “woql:subject” {“@type” “woql:Node”, “woql:node” (str “doc:” (gensym))}, “woql:predicate” {“@type” “woql:Node”, “woql:node” (str “scm:” (gensym))}, “woql:object” {“@type” “woql:Node”, “woql:node” (str “doc:” (gensym))}}) (def n 100) (def acm (clj-http.conn-mgr/make-reusable-async-conn-manager {:threads n :default-per-route n})) (declare […]

Idiomatically refactor Clojure code to improve performance

;; http://johnj.com/from-elegance-to-speed.html (def times (iterate #(+ % (rand-int 1000)) 0)) (def times-v (into [] (take 1e6) (iterate #(+ % (rand-int 1000)) 0))) (defn smt-8 [times] (->> times (partition 8 1) (map (juxt identity (comp (partial apply -) (juxt last first)))) (filter (comp (partial > 1000) second)) doall)) (cc/quick-bench (smt-8 times-v)) (defn sliding ([^long n] (sliding […]

Generate :npm-deps in deps.cljs from package.json using nbb

(ns update-deps (:require [“fs” :as fs] [clojure.edn :as edn] [clojure.pprint :refer [pprint]])) (let [package (js/require “../package.json”) js-deps (js->clj (aget package “dependencies”)) deps (edn/read-string (fs/readFileSync “src/deps.cljs” “utf8”)) deps-updated (assoc deps :npm-deps js-deps)] (binding [*print-fn* (fn [s] (fs/writeFileSync “src/deps.cljs” s))] (pprint deps-updated)))