使用 State monad 还是递归传递状态更好?
我正在学习 Haskell,并试图找出实现视线算法的最惯用的方法。
我发现的演示代码使用状态单子,但对我来说(我只是一个初学者)递归地传递状态似乎更简单。我在这里缺少什么?是否存在性能问题?
代码位于:http://www.finalcog.com/bresenham-algorithm-idiomatic-haskell谢谢
,
克里斯。
I'm just learning Haskell, and trying to figure out the most idiomatic way to implement a line of sight algorithm.
The demo code I found uses the state monad, but it seem simpler to me (I'm just a beginner) to pass state recursively. What am I missing here? Are there performance problems?
Find code at: http://www.finalcog.com/bresenham-algorithm-idiomatic-haskell
Thanks,
Chris.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
到处传递状态可能会变得有点冗长。此外,状态 monad 是大多数 Haskell 程序员所熟知的,因此他们会知道你在做什么。如果您在 monad 之外手动编写自己的代码,那么识别代码的作用可能会很棘手。
我发现状态单子很适合封装状态更改,很明显代码的哪一部分是有状态的(即改变或依赖于状态),而其余的纯粹的东西。
It can become a bit verbose to pass state everywhere. Also, the state monad is well known by most haskell coders so they'll know what you're doing. If you hand-roll your own, outside a monad, it can be tricky to discern what your code does.
I find the state monad neat for encapsulating state changes, it's pretty obvious what part of your code is stateful (i.e. alters or depends on state) w.r.t. the rest of the pure stuff.
对于较大的程序,最好将状态传递管道隐藏在 monad 中。那么出错的风险就较小。
For larger programs, it is better to hide the state passing plumbing in the monad. There is less risk of error then.
使用 monad 传递状态而不是显式传递状态的一个优点是,为 monad 定义了许多有用的组合器可供使用。
An advantage of using a monad to pass on state rather than passing on state explicitly, is that there are many useful combinators defined for monads that you can use.