| ID | 24deb51c-0f94-4455-9de8-26b3cbd1c46a |
|---|---|
| DeertopiaVisibility | public |
Clojure
Clojure is a Lisp designed for functional programming on the JVM.
Syntactic sugar
Hashfns — lambda shorthand
#(something) ; => (fn [] (something))
#(something %) ; => (fn [x] (something x))
#(something %1 %2) ; => (fn [x y] (something x y))
Java constructors
(ClassName. x y z) ; => (new ClassName x y z)
Cookbook
Trivial HTTP server
A basic HTTP server using http-kit, which is included with Babashka.
(require '[org.httpkit.server :as server]
'[clojure.pprint :refer [pprint]])
(defn app [req]
(println "\n----\n")
(pprint req)
{:status 200
:headers {"Content-Type" "text/html"}
:body "hello HTTP!"})
;; Start server.
(def my-server
(server/run-server app
{:port 8080
:legacy-return-value? false}))
Note that server/run-server is asynchronous; the most convenient way to play with this snippet is something along the lines of
$ nix-shell -p babashka rlwrap [nix-shell]$ rlwrap bb > (load-file "«your file».clj") #'user/my-server > (server/server-status my-server) ; Check that it's running correctly. :running ; Yay!
See the http-kit wiki and (doc server/run-server).
Dynamic variables
Define with
(def ^:dynamic *dry-run?* false)
Common issues
No matching ctor
Syntax error (IllegalArgumentException) compiling new at (*cider-repl src/org-access-publish:localhost:38719(clj)*:296:7). No matching ctor found for class com.unboundid.ldap.sdk.DN
Here, ctor is an abbreviation for "constructor."
Multimethods
The defmulti macro takes a function that maps the dispatch value to the "actual" dispatch value used in the hierarchy.
Sexp comments
Sexp comments can be "stacked" to comment out more than one expression in sequence:
{:blah 123
;; Stack two sexp comments to discard both the key and the value.
#_#_
:commented-key "commented-value"}