哈斯克尔懒惰和严格单子(或变形金刚)之间的区别 [英] Difference between Haskell's Lazy and Strict monads (or transformers)

查看:124
本文介绍了哈斯克尔懒惰和严格单子(或变形金刚)之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

浏览Hackage时,大部分monad都有一个Lazy和Strict版本。究竟有什么区别?你能突出显示一些常见单子(State,Reader,Writer)的例子吗?

解决方案

我不知道(T)和 Writer(T)的原因分为懒惰和严格的读者monad,分离不适用。



懒惰和严格 Writer monads resp。他们的monad变换器是一元绑定(>> =) fmap 等的实现。 (code>(result,state),resp。(result,message)的实现模式匹配, ),强迫它的评估(而不是评估它的组件​​),而懒惰的版本在那里使用了一个无可辩驳的模式〜(a,w)这不会强制对这对评价。



懒惰版本允许一些不适用于严格版本的应用程序,例如

  foo = do 
xs < - 取100个`fmap`序列(重复someAction)
doSomethingWith xs

序列无限列表操作只能在(>> =) monad是足够懒的。 另一方面,使用懒惰版本通常导致大型图钉的堆积ks在(result,state)对中,从而导致空间和/或时间泄漏。



提供变体,您可以选择更适合您的需求。


When browsing Hackage, most of the monads have a Lazy and a Strict version. What is the difference exactly? Can you highlight it with some examples for the common monads (State, Reader, Writer)?

解决方案

I don't know of a separation into lazy and strict for the reader monad, the reason for the State(T) and Writer(T) separation doesn't apply there.

The difference between the lazy and strict Writer and State monads resp. their monad transformers is the implementation of the monadic bind (>>=), fmap etc. In the strict versions, the implementation pattern-matches on the pair ((result, state), resp. (result, message)), forcing its evaluation (not the evaluation of its components), while the lazy versions use an irrefutable pattern ~(a,w) there, which does not force the evaluation of the pair.

The lazy versions allow some applications that are not possible for the strict versions, e.g.

foo = do
    xs <- take 100 `fmap` sequence (repeat someAction)
    doSomethingWith xs

the sequence of an infinite list of actions can only start delivering its result if the (>>=) of the monad is sufficiently lazy.

On the other hand, using the lazy versions often leads to the build-up of large thunks in the (result, state) pairs, and thus to space and/or time leaks.

So both variants are offered, and you can choose which suits your needs better.

这篇关于哈斯克尔懒惰和严格单子(或变形金刚)之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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