在Clojure中处理纯度错误?

时间:2015-06-12 14:46:51

标签: exception-handling clojure functional-programming either

我正在使用大爆炸式编程开发游戏,其中将整个状态定义为单个数据结构,并通过交换单个原子来管理状态变化。

在游戏中,我们不能信任客户端发送的数据,因此服务器必须预测某些移动无效并防范它的可能性。当一个人写一个交换世界状态的函数时,它可以开始纯粹;但是,必须考虑无效请求的可能性。我相信在惯用语Clojure中会产生不愉快的路径,只会抛出异常。因此,现在可能是纯粹的功能会受到副作用异常的影响。也许this可能就是这样。

(try
  (swap! world update-game) ;possible exception here!
  (catch Exception e
    (>! err-chan e))

我的目标是将副作用推迟到最后一刻。我几乎没有进入Haskell的土地,但我知道Either monad的概念。当人们认为the happy and unhappy path时,人们会理解这两种可能性。这让我觉得swap!本身是不够的,因为它忽略了不愉快的道路。以下是这个想法的主旨:

(swap-either! err-chan world update-game) ;update-game returns either monad

Clojure社区是否已采用any more functional approaches来处理异常?

1 个答案:

答案 0 :(得分:3)

在这种情况下,我倾向于采取几种不同的方法。如果状态在一个位置更新,我倾向于:

'mysql' is not recognized as an internal or external command, operable program or batch file.

或者如果它在许多地方设置了广告,那么观察者会将异常抛回到交换的地方!被召唤并且没有改变状态:

(try
  (swap! world update-game) ;possible exception here!
  (catch Exception e
    (>! err-chan e) 
    world)  ;;  <--- return the world unchanged
相关问题