Clojure states within states within states

前端 未结 3 1945
梦谈多话
梦谈多话 2021-02-13 02:45

I\'d love to hear what advice the Clojure gurus here have about managing state in hierarchies. I find I\'m often using {:structures {:like {:this {:with {:many \'levels}}

3条回答
  •  借酒劲吻你
    2021-02-13 03:20

    You can use assoc-in, get-in, update-in, and dissoc-in functions to work with nested structures.

    They are very convenient, but I don't know if they can handle atoms and such directly. In the worst case you should be able to nest them up to deref, e.g.:

    (def m (atom {:like {:this {:nested (atom {:value 5})}}}))
    
    @(get-in @m [:like :this :nested])
    ; => {:value 5}
    
    (get-in @(get-in @m [:like :this :nested]) [:value])
    ; => 5
    

    You can use -> to make this more readable:

    (-> @m
        (get-in [:like :this :nested])
        deref
        (get-in [:value]))
    ; => 5
    

    Regarding nested atoms/refs/agents, etc. I think it depends on what you're trying to achieve. It's certainly easier to reason about things, if there's just one of them at the top and the changes are synchronized.

    On the other hand, if you don't need this synchronization, you're wasting time in doing it, and you'll be better off with nested atoms/refs/agents.

    The bottom line is, I don't think either way is "the right way", they both have their usages.

提交回复
热议问题