F# 中的加法类型 (+) [英] Type of addition (+) in F#
问题描述
我刚刚了解到 OCAML 必须有一个 .
后缀来进行浮点运算.一个例子是 3.+.4.
等于 7.
(浮点数).但是,F# 以相同的方式处理浮点数和整数运算,因此 3 + 4
(int) 和 3.+ 4.
(浮动)有效.
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 ->内部 ->整数
.事实上 (+)
给了我 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屋!