通过具有不同参数数量的方程来定义函数 [英] Defining a function by equations with different number of arguments
问题描述
我今天注意到这样一个定义
safeDivide x 0 = x
safeDivide =(/)
是不可能的。我只是好奇这背后的(好)原因是什么。必须有一个非常好的(这是Haskell毕竟:))。
注意:我没有看上述代码的替代实现的建议,这是一个简单的例子以证明我的观点。
我认为这主要是为了保持一致性,因此所有的子句都可以用相同的方式读取,说话;即每个RHS在功能类型中处于相同的位置。我认为如果你允许的话,也会掩盖一些愚蠢的错误。
还有一个轻微的语义怪癖:说编译器填充这些子句以得到相同的数字作为其他条款的模式;即你的例子将变成
safeDivide x 0 = x
safeDivide xy =(/)xy
现在考虑第二行是否为 safeDivide = undefined
;在没有前面的子句的情况下, safeDivide
会是⊥
,但是由于这里执行的eta扩展, \xy - >如果y == 0那么x else⊥
- 所以 safeDivide = undefined
实际上并没有定义 safeDivide
成为⊥
!这似乎令人困惑,足以证明禁止此类条款,国际海事组织。
I noticed today that such a definition
safeDivide x 0 = x
safeDivide = (/)
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.
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
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.
这篇关于通过具有不同参数数量的方程来定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!