问题描述
我今天注意到这样的定义
I noticed today that such a definition
safeDivide x 0 = x
safeDivide = (/)
是不可能的.我只是好奇这背后的(好的)原因是什么.一定有一个非常好的(毕竟是 Haskell :)).
is not possible. I am just curious what the (good) reason behind this is. There must be a very good one (it's Haskell after all :)).
注意:我不是在寻找上述代码的替代实现建议,这是一个简单的例子来证明我的观点.
Note: I am not looking suggestions for alternative implementations to the code above, it's a simple example to demonstrate my point.
推荐答案
我认为这主要是为了一致性,以便所有子句可以以相同的方式阅读,可以这么说;即每个 RHS 在函数类型中的相同位置.如果您也允许这样做,我认为会掩盖不少愚蠢的错误.
I think it's mainly for consistency so that all clauses can be read in the same manner, so to speak; i.e. every RHS is at the same position in the type of the function. I think would mask quite a few silly errors if you allowed this, too.
还有一个轻微的语义怪癖:假设编译器填充了这些子句,使其具有与其他子句相同数量的模式;即你的例子会变成
There's also a slight semantic quirk: say the compiler padded out such clauses to have the same number of patterns as the other clauses; i.e. your example would become
safeDivide x 0 = x
safeDivide x y = (/) x y
现在考虑第二行是否是 safeDivide = undefined
;如果没有前面的条款,safeDivide
将是 ⊥
,但由于这里执行的 eta 扩展,它是 xy ->if y == 0 then x else ⊥
— 所以 safeDivide = undefined
实际上并没有将 safeDivide
定义为 ⊥
!IMO,这似乎足以证明禁止此类条款的合理性.
Now consider if the second line had instead been safeDivide = undefined
; in the absence of the previous clause, safeDivide
would be ⊥
, but thanks to the eta-expansion performed here, it's x y -> if y == 0 then x else ⊥
— so safeDivide = undefined
does not actually define safeDivide
to be ⊥
! This seems confusing enough to justify banning such clauses, IMO.
这篇关于通过具有不同参数数量的方程定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!