Created
March 12, 2021 12:45
-
-
Save plexus/42c0cbc97455a1656471e5d31c67f122 to your computer and use it in GitHub Desktop.
Doing key lookup in Clojure
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
;; If it's a record-like thing then we want to emphasize | |
;; that it's a key-lookup, so use (:key coll) | |
(:uri req) | |
(:email member) | |
;; Some collections behave more like functions, here use (coll key), | |
;; that way someone reading the code without context can understand it, | |
;; without having to know that it's really a map or set | |
(def allowed-role? #{:admin :mod}) | |
(allowed-role? (:role user)) | |
(def message-color {:error "red" :warning "orange" :success "green"}) | |
(let [{:keys [content type]} message] | |
[:p {:style {:background-color (message-color type)}} | |
content]) | |
;; This also makes it clear that you can use functional composition | |
(def has-access? (comp allowed-role? :role)) | |
(has-access? user) | |
;; If both collection and key are variables, then (get coll key) | |
;; can help keep things readable, because it's explicit about | |
;; the roles of its arguments | |
(def flags {:f "-format" :d "-duration"}) | |
(defn cli-args [opts] | |
(for [[k v] opts] | |
(str (get flags k) " " v))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment