Created
September 16, 2017 11:18
-
-
Save Olical/f2b934873a49c0638ca673ab764a0131 to your computer and use it in GitHub Desktop.
Using clojure.spec to parse trees
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
(ns bonsai.tree | |
(:require #?(:clj [clojure.spec.alpha :as s] | |
:cljs [cljs.spec.alpha :as s]))) | |
(s/def ::element (s/or :string string? | |
:element (s/cat :name keyword? | |
:attrs (s/? (s/map-of keyword? any?)) | |
:children (s/* ::element)))) | |
(s/conform ::element [:p]) | |
;; => | |
;; [:element {:name :p}] | |
(s/conform ::element [:p "hey!"]) | |
;; => | |
;; [:element {:name :p, | |
;; :children [[:string "hey!"]]}] | |
(s/conform ::element [:p {:on-click println} "hey!"]) | |
;; => | |
;; [:element {:name :p, | |
;; :attrs {:on-click #f | |
;; unction | |
;; [clojure.core/println]}, | |
;; :children [[:string "hey!"]]}] | |
(s/conform ::element [:p | |
{:on-click println} | |
[:span "before"] "middle" [:span "after"]]) | |
;; => | |
;; [:element {:name :p, | |
;; :attrs {:on-click #function | |
;; [clojure.core/println]}, | |
;; :children [[:element {:name :span, | |
;; :children [[:string "before"]]}] | |
;; [:string "middle"] | |
;; [:element {:name :span, | |
;; :children [[:string "after"]]}]]}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment