F#中的加法类型(+) [英] Type of addition (+) in F#
问题描述
我刚刚了解到OCAML必须具有.
后缀才能进行浮点运算.一个示例是3. +. 4.
,它等于7.
(浮点数).但是,F#以相同的方式处理浮点和整数算术,因此3 + 4
(int)和3. + 4.
(float)均可工作.
I just learned that OCAML have to have a .
postfix for doing float arithmetic. An example would be 3. +. 4.
which equals 7.
(float). However, F# handles float and integer arithmetic in the same way, so both 3 + 4
(int) and 3. + 4.
(float) works.
F#自然地将+
分配给int,因此let add a b = a + b
的类型为int -> int -> int
.确实(+)
给了我val it : (int -> int -> int) = <fun:it@6-1>
.
F# have +
naturally assigned to int so let add a b = a + b
is of type int -> int -> int
. And indeed (+)
gives me val it : (int -> int -> int) = <fun:it@6-1>
.
这导致以下顺序,我认为这是违反直觉的:
That leads to the following sequence which I think quite counter-intuitive:
> 3. + 4.;;
val it : float = 7.0
> (+);;
val it : (int -> int -> int) = <fun:it@8-2>
所以我的问题是:是由编译器中的特殊机制/情况完成的重载"还是这是一种语言范围的事情,因此我可以定义一个名为add
的函数(或其他形式),其中一个定义为整数,一个定义为浮点数(或任何其他类型).
So my question is: Is the "overloading" done by a special mechanism/case in the compiler or is this a language-wide thing so I potentially can define a function called add
(or anything else) which have a one definition for integers and one for floats (or any other type.)
推荐答案
简而言之,F#通过inline
关键字和静态成员约束"具有临时重载机制.内置数学运算符还具有其他一些特殊的魔术,神奇地假定类型int
没有其他约束. (+)
几乎是F#中最特殊/最神奇的东西,因此并不能很好地介绍语言/类型系统.
Briefly, F# has an ad-hoc-overloading mechanism via the inline
keyword and "static member constraints". There is some further magic specific to the built-in math operators, which magically assumes type int
the absence of other constraints. (+)
is just about the most special/magical thing in all of F#, so it does not make for a nice introduction to the language/type system.
通常,对于静态类型的,类型推断的语言,重载"是很难的. F#在这里的选择非常实用. OCaml会执行不同的,简单的,实用的操作(不重载). Haskell做另一种复杂但优雅的事情(类型类).它们都是语言/库设计空间中的合理点.
In general, "overloading" is difficult for statically-typed, type-inferred languages. F#'s choices here are very pragmatic. OCaml does a different, simple, pragmatic thing (no overloading). Haskell does a different, complex-but-elegant thing (type classes). They're all somewhat reasonable points in the language/library design space.
这篇关于F#中的加法类型(+)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!