Skip to content

Instantly share code, notes, and snippets.

@roman01la
Created February 4, 2018 16:46
Show Gist options
  • Save roman01la/89579cdf17c59da516e6f850d25d2ea1 to your computer and use it in GitHub Desktop.
Save roman01la/89579cdf17c59da516e6f850d25d2ea1 to your computer and use it in GitHub Desktop.
Parsing with clojure.spec
(require '[clojure.spec.alpha :as s])
[:h1 {} "0" 1 [:span]]
(s/def :hiccup/form
(s/or
:string string?
:number number?
:element :hiccup/element))
(s/def :hiccup/element
(s/cat
:tag keyword?
:attrs (s/? map?)
:children (s/* :hiccup/form)))
(defn parse-hiccup [hiccup]
(s/conform :hiccup/form hiccup))
(defmulti html first)
(defmethod html :string [[_ v]]
v)
(defmethod html :number [[_ v]]
v)
(defmethod html :element [[_ {:keys [tag attrs children]}]]
(str "<" (name tag) ">"
(->> (map html children)
(clojure.string/join ""))
"</" (name tag) ">"))
(html (parse-hiccup [:h1 {} "Hello" [:span "1" 2]]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment