首页 > 解决方案 > 如何访问clojure中的原子元素

问题描述

(def input (atom[
#{
  [
    {:site-id 1} 
    {:both-unconf [[27 4] "Humidity"]} 
    {:own-unconf|other-conf [[30 1] "Humidity"]} 
    {:other-site-unconf 2500} 
    {:other-site-conf 2500} 
      [
        {:site-id 0} 
        {:both-unconf [[20 1] "Temperature"]} 
        {:own-unconf|other-conf [[22 0] "Temperature"]} 
        {:other-site-unconf 3} 
        {:other-site-conf 1}
      ]
  ]
} :something-else
]))

我想从这个 atom map 访问 site-id。

我正在使用以下代码,但没有得到输出。

(->> @input
     (map #(:site-id %))
     (into [])

标签: clojure

解决方案


(def input
  (atom [#{[{:site-id 1}
            {:both-unconf [[27 4] "Humidity"]} 
            {:own-unconf|other-conf [[30 1] "Humidity"]} 
            {:other-site-unconf 2500} 
            {:other-site-conf 2500} 
            [{:site-id 0} 
             {:both-unconf [[20 1] "Temperature"]} 
             {:own-unconf|other-conf [[22 0] "Temperature"]} 
             {:other-site-unconf 3} 
             {:other-site-conf 1}]]}
         :something-else]))

这个数据结构很奇怪。这是

  • 一个原子,包含
  • 一个向量,包含
  • 一个集合,包含
  • 一个向量,包含
  • 一堆单键地图,然后
  • 另一个向量,包含
  • 一堆单键地图
  • 等等,大概

如果我们允许:something-else是别的东西,它应该是有用的:

  • 一个原子,包含
  • 一个向量,包含
  • 一个集合,包含
  • 一堆地图

所以:

(def input
  (atom [#{{:site-id 1
            :both-unconf [[27 4] "Humidity"]
            :own-unconf|other-conf [[30 1] "Humidity"]
            :other-site-unconf 2500
            :other-site-conf 2500} 
           {:site-id 0
            :both-unconf [[20 1] "Temperature"]
            :own-unconf|other-conf [[22 0] "Temperature"]
            :other-site-unconf 3
            :other-site-conf 1}}
         :something-else]))

如果是这样的话,那么

(->> @input
     first
     (mapv :site-id))

会工作。


推荐阅读