Skip to content

Instantly share code, notes, and snippets.

@humorless
Forked from roman01la/core.clj
Created October 1, 2019 15:52
Show Gist options
  • Save humorless/b7bd12775694b16efb6bd1053fe68f96 to your computer and use it in GitHub Desktop.
Save humorless/b7bd12775694b16efb6bd1053fe68f96 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