Last active
January 1, 2016 08:18
-
-
Save rwat/8116957 to your computer and use it in GitHub Desktop.
Sundry Clojure snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; current time | |
(System/currentTimeMillis) | |
;; make a version 4 random UUID as per http://www.ietf.org/rfc/rfc4122.txt | |
(java.util.UUID/randomUUID) | |
;; start a new thread and run a function | |
(.start (Thread. (fn [] (loop [] | |
(do | |
(update-mock-data!) | |
(Thread/sleep 1000)) | |
(recur))))) | |
;; stringify data for sending over the network | |
(pr-str {:hi "there"}) | |
;; read data safely from untrusted sources (like a browser) | |
(ns blah | |
(:require [clojure.tools.reader :as edn])) | |
(edn/read-string data) | |
;; read from a file line by line and write each line to another file | |
(ns foo | |
(:require [clojure.java.io :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 (java.io 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 [] | |
(alt! | |
foo ([msg] (prn "From foo: " foo)) | |
bar ([msg] (prn "From bar: " bar)) | |
[baz sth] ([msg _] (>! ch msg)))) | |
;; see also, "fan-in" from https://github.com/martintrojer/go-tutorials-core-async/blob/f0e178011184d1d6a1846104c1be2829407d25f0/src/tut104.clj | |
(defn fan-in [in1 in2] | |
(let [ch (chan)] | |
(go-loop [] | |
;; note alt! result-expr syntax | |
(alt! [in1 in2] | |
([msg _] (>! ch msg))) | |
(recur)) | |
ch)) | |
;(go | |
; (<! 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