F#中的加法类型(+)

编程入门 行业动态 更新时间:2024-10-23 03:27:33
本文介绍了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#中的加法类型(+)

本文发布于:2023-07-30 15:17:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1250560.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加法   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!