为什么乘法只在一侧短路 [英] Why does multiplication only short circuit on one side

查看:108
本文介绍了为什么乘法只在一侧短路的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在乱搞 fix ,在弄乱它之后,我发现了一些奇怪的行为,即 0 * undefined ***例外:Prelude.undefined undefined * 0 0 。这也意味着 fix(0 *) ***例外:<< loop>> fix(* 0) 0



After玩弄它似乎是因为它使得它在两个方向上短路并非微不足道,因为这没有多大意义,没有某种奇怪的并行计算并从第一个非底部开始返回。



在其他地方看到这种东西(反射函数不是底值的反射函数),是我可以安全依赖的东西吗?还有一种实际的方法可以将(0 *)(* 0)评估为零,而不管值传入。

解决方案

你的推理是正确的。有一个 unamb 软件包,可为你提到的那种并行计算。事实上,它提供了 Data.Unamb.pmult ,它并行地尝试检查每个操作数是1还是0,如果是,立即产生结果。在大多数情况下,对于简单的算术,这种并行方法可能会慢得多! GHC版本7.10中只出现 。它是由于在GHC版本中对 Integer 类型的实现进行了更改的结果。这种额外的懒惰通常被视为一种性能缺陷(因为它会干扰严格性分析,甚至会导致理论上的空间泄漏),所以它将在GHC 8.0中被删除。


I was messing around with fix and after messing around with it I came across some weird behavior, namely that 0 * undefined is *** Exception: Prelude.undefined and undefined * 0 is 0. Which also means that fix (0 *) is *** Exception: <<loop>> and fix (* 0) is 0.

After playing around with it it seems like the reason is because it is non-trivial to make it short circuit in both directions, as that doesn't really make much sense, without some sort of weird parallel computation and start with the first non-bottom returned.

Is this kind of thing seen in other places (reflexive functions that aren't reflexive for bottom values), and is it something I can safely rely on? Also is there a practical way to make both (0 *) and (* 0) evaluate to zero regardless of the value passed in.

解决方案

Your reasoning is correct. There is an unamb package providing tools for the sort of parallel computation you refer to. In fact, it offers Data.Unamb.pmult, which tries, in parallel, to check whether each operand is 1 or 0, and if so immediately produces a result. This parallel approach is likely to be much slower in most cases for simple arithmetic!

The short-circuiting of (*) occurs only in GHC version 7.10. It came about as a result of changes to the implementation of the Integer type in that GHC version. That extra laziness was generally seen as a performance bug (as it interferes with strictness analysis and can even lead to space leaks in theory), so it will be removed in GHC 8.0.

这篇关于为什么乘法只在一侧短路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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