Skip to content

Instantly share code, notes, and snippets.

@rwat rwat/clojure_snippets.clj
Last active Jan 1, 2016

What would you like to do?
Sundry Clojure snippets
;; current time
;; make a version 4 random UUID as per
;; start a new thread and run a function
(.start (Thread. (fn [] (loop []
(Thread/sleep 1000))
;; stringify data for sending over the network
(pr-str {:hi "there"})
;; read data safely from untrusted sources (like a browser)
(ns blah
(:require [ :as edn]))
(edn/read-string data)
;; read from a file line by line and write each line to another file
(ns foo
(:require [ :as io]))
(with-open [r (io/reader "/home/username/input.txt")
w (io/writer "/home/username/output.txt")]
(doseq [line (line-seq r)]
(let [s (str line "\n")]
(.write w s 0 (count s)))))
;; read from a RandomAccess file
(ns foo
(:import ( RandomAccessFile)))
(let [begin (bar)
end (baz)
ba (byte-array (- end begin))]
(with-open [file (RandomAccessFile. (str path filename) "r")]
(doto file
(.seek begin)
(.read ba)))
(prn (String. ba "UTF-8")))
;; using alt!
(def ch (chan))
(go-loop []
foo ([msg] (prn "From foo: " foo))
bar ([msg] (prn "From bar: " bar))
[baz sth] ([msg _] (>! ch msg))))
;; see also, "fan-in" from
(defn fan-in [in1 in2]
(let [ch (chan)]
(go-loop []
;; note alt! result-expr syntax
(alt! [in1 in2]
([msg _] (>! ch msg)))
; (<! readystate)
; (while true
; (let [[val ch] (alts! [socketinput socketoutput])]
; (cond
; (= ch socketinput) (print "received websocket input: " val)
; (= ch socketoutput) (do
; (print "I have something to send: " val)
; (.send @socket (pr-str val)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.