Clojure在州内的状态 [英] Clojure states within states within states

查看:104
本文介绍了Clojure在州内的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想听听Clojure大师在这里对层次结构管理状态的建议。我发现我经常使用 {:结构{:像{:this {:with {:many'levels}}}}} 状态,通过在值(atom {:like(atom'this)})周围引用原子,我发现自己认为这一定是错误的。通常最好只在顶层使用一个原子,而在地图中没有值作为值?

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}} } } } and if I want to track changes in state at multiple levels, by throwing atoms around values (atom {:like (atom 'this)} ), I find myself thinking this must be wrong. Is it generally better to use just one atom at the top level, and have none as values in a map ?

推荐答案

如果可能,不要在数据结构中使用嵌套原子。

主要原因是不可变性是您的朋友。 Clojure是一种在不变数据结构上蓬勃发展的函数式语言。大多数库假定不可变的数据结构。 Clojure的STM假定不可变的数据结构来获得最好的并发性。不变性使您有机会在任何一个瞬间获取整个状态的一致快照。对不可变数据进行操作的纯函数很容易开发和测试。

The main reason is that immutability is your friend. Clojure is a functional language that thrives on immutable data structures. Most libraries assume immutable data structures. Clojure's STM assumes immutable data structures to get the best possible concurrency. Immutability gives you the opportunity to take consistent snapshots of the entire state at any one instant. Pure functions that operate on immutable data are easy to develop and test.

如果你把原子放在数据结构中,那么你会失去不变性的所有优点,

If you put atoms inside your data structures then you lose all the advantages of immutability and risk making your code very complex - it's a lot harder to reason about a data structure if it contains a lot of mutable components.

一些建议的替代方法:


  • 将整个数据结构放在单个引号或原子中。这可能是一个巨大的数据结构没有问题 - 我曾经写过一个游戏,整个游戏地图是在一个原子没有任何困难。

  • 使用设计的各种方法访问和更改嵌套的不可变数据结构: assoc-in get-in update-in 等。

  • 使用递归函数使您的数据结构更易于管理。如果你的结构的一个节点具有相同类型的子节点,那么它通常是一个很好的提示,你应该使用某种形式的递归函数。

  • Put your entire data structure in a single ref or atom. This can be a huge data structure with no problem - I once wrote a game where the entire game map was held in a single atom without any difficulty.
  • Use the various methods that are designed for accessing and changing nested immutable data structures: assoc-in, get-in, update-in etc.
  • Use recursive functions to make navigating your data structure more managable. If one node of your structure has sub-nodes of the same "type" then it's usually a good hint that you should be using some form of recursive function.

这篇关于Clojure在州内的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆