Haskell 中 == 和 = 的区别
我仍然无法理解 Haskell 中 ==
和 =
之间的区别。我知道前者与重载类型有关,后者“给出函数的结果”,但我似乎无法理解它!任何帮助将不胜感激。
I still have trouble getting my head around the difference between the ==
and =
in Haskell. I know the former has something to do with being an overloaded type and the latter 'gives the result' of the function but I just can't seem to get my head around it! Any help would be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
=
是 Haskell 中的一个特殊保留符号,意思是“定义为”。它用于引入定义。也就是说,您使用它来创建可以在其他值和函数的定义中引用的新值和函数。==
不是保留符号,而只是Eq a => 类型的普通函数。一个->一个->布尔。它恰好在 类型类 (
Eq
) 中声明,但并没有什么特别之处。您可以隐藏==
的内置声明并将其重新定义为您想要的任何内容。但通常它意味着“等于”,并且因为它是类型类的一部分,所以您可以定义(重载)它来表示您希望“相等”对您的特定类型意味着的任何内容。例如:
请注意,我使用
=
为Foo
定义==
!思考差异的简洁方式是
=
在编译时断言相等,而==
检查运行时相等。=
is a special reserved symbol in Haskell meaning "is defined as". It is used to introduce definitions. That is, you use it to create new values and functions which may be referenced in the definitions of other values and functions.==
is not a reserved symbol but just a run-of-the-mill function of typeEq a => a -> a -> Bool
. It happens to be declared in a type class (Eq
), but there's nothing extraordinary about it. You could hide the built-in declaration of==
and redefine it to whatever you wanted. But normally it means "is equal to", and because it is part of a type class, you can define (overload) it to mean whatever you want "equality" to mean for your particular type.For example:
Note that I used
=
to define==
forFoo
!A pithy way to think of the difference is that
=
asserts equality at compile time, whereas==
checks for equality at runtime.=
执行赋值。或者定义可能是一个更好的词。只能做一次。这是一个特殊的运算符/符号。它不是一个函数==
是一个函数,通常是中固定的,它接受类型类Eq
的两个输入并返回一个 bool=
performs assignment. or definition is probably a better word. can only do it once. this is a special operator/symbol. it is not a function==
is a function, usually infixed, that takes two inputs of typeclassEq
and returns a bool我还不是一个 Haskell 专家,但与大多数其他语言一样,
==
是一个比较运算符,产生true
或false
,而 < code>= 是赋值运算符,在 Haskell 中可以归结为函数声明。I'm not quite a Haskell expert yet, but as in most other languages
==
is a comparison operator yieldingtrue
orfalse
, while=
is the assignment operator, which in Haskell boils down to function declaration.== 是一个用于比较两个事物是否相等的运算符。这是非常正常的 haskell 函数,类型为“Eq a => a -> a -> Bool”。该类型表明它适用于实现 Eq 类型类的值的每种类型,因此它有点重载。
另一方面,= 是一个赋值运算符,用于引入定义。
The == is an operator for comparing if two things are equal. It is quite normal haskell function with type "Eq a => a -> a -> Bool". The type tells that it works on every type of a value that implements Eq typeclass, so it is kind of overloaded.
The = on the other hand is an assignment operator, which is used to introduce definitions.
== 表示相等
示例:比较两个整数
= 表示赋值
示例:将整数分配给变量
== is for equality
example: comparing two integers
= is assignment
example: assigning an integer to a variable