大佬教程收集整理的这篇文章主要介绍了如何遍历复杂的地图并根据 Clojure 中的模式删除键?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我对 Clojure 还很陌生,如果这是一个愚蠢的问题,我很抱歉,但我有一个相当复杂的地图(它包含嵌套地图、向量等)。在我将它放入我的数据库之前,我基本上想分离一堆我不需要保存写入速度的东西(在这种情况下,这是一个显着的性能改进)。我想通过制作某种模式来过滤掉我不需要的所有位,该模式可用于删除任何不必要的内容。这是我想要实现的那种事情的一个例子(奇怪的例子,抱歉!):
(def my-book
{:intro {:one-liners [{:line "wowza" :raTing 7}
{:line "cool!" :raTing 4}]}
:how-many-lines 10
:rubbish-one-liners [{:line "bongo" :raTing 1}
{:line "foo" :raTing 2}]
:other-info {:author {:name "me" :age 24}}})
(def my-scheR_79_11845@a
[{:intro [{:one-liners {:values [:line :raTing]}}
{:values [:how-many-lines]}
{:rubbish-one-liners {:values [:line]}}
{:other-info {:author {:values [:name]}}}]}])
;;expected output when filtering via the scheR_79_11845@a:
(def my-output
{:intro {:one-liners [{:line "wowza" :raTing 7}
{:line "cool!" :raTing 4}]}
:how-many-lines 10
:rubbish-one-liners [{:line "bongo"}
{:line "foo"}]
:other-info {:author {:name "me"}}})
我不确定该模式是否是处理它/结构的最佳方式,一旦我有了一个模式,如何实际处理它,因为似乎涉及很多不同的数据结构- 所以我想我的问题是,你如何建议我遍历我拥有的任何结构并根据模式删除键? :) 谢谢!
Clojure 有 SELEct-keys,你只需要对嵌套结构使用递归。尝试这样的事情:
(defn key-filter [obj scheR_79_11845@a]
(cond
(vector? obj) (map #(SELEct-keys % scheR_79_11845@a) obj)
(map? obj)
(let [nw (SELEct-keys obj (keys scheR_79_11845@a))
res (map key-filter (vals nw) (vals scheR_79_11845@a))]
(zipmap (keys nw) res))
:else obj))
(def my-book {:intro {:one-liners [{:line "wowza",:raTing 7} {:line "cool!",:raTing 4}],:how-many-lines 10,:rubbish-one-liners [{:line "bongo",:raTing 1} {:line "foo",:raTing 2}],:other-info {:author {:name "me",:age 24}}}})
(def my-scheR_79_11845@a {:intro {:one-liners [:line],:how-many-lines [],:rubbish-one-liners [:line],:other-info {:author {:name []}}}})
(key-filter my-book my-scheR_79_11845@a)
,
没有全面的库可以接受模式并通过删除额外的键等来强制数据结构与模式匹配。此外,您的模式和书籍结构之间存在一些不一致,例如哪些字段是向量或不是。
首先,我将使用 Spectre 库并手动编写所需的转换。一个例子:
(ns tst.demo.core
(:use tupelo.core tupelo.test)
(:require
[com.rpl.specter :as sp]))
(dotest
(let [book {:intro {:one-liners [{:line "wowza" :raTing 7}
{:line "cool!" :raTing 4}]}
:how-many-lines 10
:rubbish-one-liners [{:line "bongo" :raTing 1}
{:line "foo" :raTing 2}]
:other-info {:author {:name "me" :age 24}}}
expected {:intro {:one-liners [{:line "wowza" :raTing 7}
{:line "cool!" :raTing 4}]}
:how-many-lines 10
:rubbish-one-liners [{:line "bongo"}
{:line "foo"}]
:other-info {:author {:name "me"}}}]
(is= expected
(it-> book
(sp/SETVAL [:rubbish-one-liners sp/ALL :raTing] sp/NONE it)
(sp/SETVAL [:other-info :author :age] sp/NONE it)))))
此代码的实例can be seen here。
请注意,Spectre 定义了一种 DSL,它本质上是一种独立的编程语言。 Spectre 非常强大,但需要一些练习和试错才能正确学习(类似于学习正则表达式语法)。
您也可以使用 the Tupelo Forest library 执行此任务。
以上是大佬教程为你收集整理的如何遍历复杂的地图并根据 Clojure 中的模式删除键?全部内容,希望文章能够帮你解决如何遍历复杂的地图并根据 Clojure 中的模式删除键?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。