Skip to content

Instantly share code, notes, and snippets.

@jaidetree
Last active June 1, 2020 03:09
Show Gist options
  • Save jaidetree/767e20e30fe7135d5aeabfcfd677ec9a to your computer and use it in GitHub Desktop.
Save jaidetree/767e20e30fe7135d5aeabfcfd677ec9a to your computer and use it in GitHub Desktop.
A quick example to spec a tree-like data structure consisting of leafs, recursive nodes, and an empty list
(ns spec-intro.core
(:require
[clojure.spec.alpha :as s]))
(s/def ::tree (s/or
:empty (s/and coll? empty?)
:node (s/cat :left (s/? ::tree)
:right (s/? ::tree))
:leaf (complement coll?)))
(def tree [0 [1 [2 [3 []]]]])
[(s/conform ::tree tree)
(s/conform ::tree [1 0])
(s/conform ::tree [])
(s/conform ::tree 1)]
;; =>
[[:node
{:left [:leaf 0],
:right
[:node
{:left [:leaf 1],
:right
[:node
{:left [:leaf 2],
:right [:node {:left [:leaf 3], :right [:empty []]}]}]}]}]
[:node {:left [:leaf 1], :right [:leaf 0]}]
[:empty []]
[:leaf 1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment