我正在尝试在clojure中创建一个简单的文本编辑器,以便熟悉它。我正在考虑为结构使用拉链以及导航和更新编辑器。
我在考虑将编辑器的文本存储在类似的文档中:
(def document-test {
:id "doc1"
:info {
:title "Moluctular bio"
:description "Test document"
}
:nodes [{
:type "header"
:content "This is a header"
:id "h1"
}
{
:type "p"
:content "this is a paragraph"
:id "p1"
}
{
:type "todo"
:content "Todo list"
:id "t1"
:nodes [
{
:type "todoelement"
:content "Do this"
:id "td1"
}
{
:type "todoelement"
:content "Do that"
:id "td2"
}]}]})
所以我想制作一个能够轻松导航的拉链。拉链可能不是最好的吗?但我想从根本开始。下来会带你到那些孩子的节点。所以文档的顶部是id h1。
我有以下内容,但它不允许孩子成为一个数组:
(defn map-zip [m]
(zip/zipper
#(map? (second %))
#(seq (second %))
(fn [node children] [(first node) (into {} children)])
[:root m]))
它更期待像:
{:foo {:bar {:baz 2}}}
有什么想法?如果有人有任何建议,我愿意完全改变结构。
答案 0 :(得分:1)
您可以构建拉链来导航该结构,如下所示:
(def z (zip/zipper
(constantly true) ; a node can always have children
:nodes ; child nodes in the :nodes key, and keywords are functions
(fn [node children]
(update-in node [:nodes] #(into (or % []) children)))
document-test))
(-> z
zip/down
zip/right
zip/right
(zip/insert-child {:type "h3" :id "thing1" :content "It's a h3!"})
zip/down
zip/right
zip/right
zip/node)
您可能还想查看Enlive或Instaparse的解析树格式,以了解有关结构的想法。重复使用它们的结构可能会为您提供一些互操作性,而这些功能是您自己编写的。