这些功能有什么不同?
What is so different about these functions?
我有一个函数:
fn x => x
现在,参数 x 既适用于 real 也适用于 int(例如 (x:real))。这两个函数的不同之处和相同之处,尽管它们似乎有效地做同样的事情:
1. fn (x:int) => x;
2. fn (x:real) => x;
这两个函数都接受 x 的输入和输出 x。
但是,在第一个函数中,输入 x 被强制转换 为 int 类型,而第二个被强制转换为 int输入 real.
因此第一个函数的类型为 (int -> int)
,第二个函数的类型为 (real -> real)
。
三个都是恒等函数,但后两个不是多态的
非多态版本不完全相同 – 一个具有类型 int -> int
,另一个具有类型 real -> real
,因此它们只能分别应用于 int
和 real
.
示例:
Standard ML of New Jersey v110.79 [built: Wed Oct 7 00:59:52 2015]
fn (x:int) => x;
val it = fn : int -> int
- fn (x:real) => x;
val it = fn : real -> real
- (fn (x:int) => x) 3;
val it = 3 : int
- (fn (x:int) => x) 3.0;
stdIn:2.1-2.22 Error: operator and operand don't agree [tycon mismatch]
operator domain: int
operand: real
in expression:
(fn x : int => x) 3.0
- (fn (x:real) => x) 3;
stdIn:1.2-1.22 Error: operator and operand don't agree [overload conflict]
operator domain: real
operand: [int ty]
in expression:
(fn x : real => x) 3
- (fn (x:real) => x) 3.0;
val it = 3.0 : real
相比之下,多态版本适用于一切:
- fn x => x;
val it = fn : 'a -> 'a
- (fn x => x) 3.0;
val it = 3.0 : real
- (fn x => x) 3;
val it = 3 : int
- (fn x => x) "hello";
val it = "hello" : string
- (fn x => x) [1,2,3];
val it = [1,2,3] : int list
在1.和2.中,您不是在应用函数,而是在指定类型。为了应用该功能,写 (fn x => x) 5
和 fn x => x) 5.0
。当您执行此函数应用程序时,确实推断出 x 具有您显式编写的类型。
下面两个函数的区别在于它们采用不同的类型。这两个函数之间的相似之处在于它们对输入执行相同的操作,即它们只是将其返回。
我有一个函数:
fn x => x
现在,参数 x 既适用于 real 也适用于 int(例如 (x:real))。这两个函数的不同之处和相同之处,尽管它们似乎有效地做同样的事情:
1. fn (x:int) => x;
2. fn (x:real) => x;
这两个函数都接受 x 的输入和输出 x。
但是,在第一个函数中,输入 x 被强制转换 为 int 类型,而第二个被强制转换为 int输入 real.
因此第一个函数的类型为 (int -> int)
,第二个函数的类型为 (real -> real)
。
三个都是恒等函数,但后两个不是多态的
非多态版本不完全相同 – 一个具有类型 int -> int
,另一个具有类型 real -> real
,因此它们只能分别应用于 int
和 real
.
示例:
Standard ML of New Jersey v110.79 [built: Wed Oct 7 00:59:52 2015]
fn (x:int) => x;
val it = fn : int -> int
- fn (x:real) => x;
val it = fn : real -> real
- (fn (x:int) => x) 3;
val it = 3 : int
- (fn (x:int) => x) 3.0;
stdIn:2.1-2.22 Error: operator and operand don't agree [tycon mismatch]
operator domain: int
operand: real
in expression:
(fn x : int => x) 3.0
- (fn (x:real) => x) 3;
stdIn:1.2-1.22 Error: operator and operand don't agree [overload conflict]
operator domain: real
operand: [int ty]
in expression:
(fn x : real => x) 3
- (fn (x:real) => x) 3.0;
val it = 3.0 : real
相比之下,多态版本适用于一切:
- fn x => x;
val it = fn : 'a -> 'a
- (fn x => x) 3.0;
val it = 3.0 : real
- (fn x => x) 3;
val it = 3 : int
- (fn x => x) "hello";
val it = "hello" : string
- (fn x => x) [1,2,3];
val it = [1,2,3] : int list
在1.和2.中,您不是在应用函数,而是在指定类型。为了应用该功能,写 (fn x => x) 5
和 fn x => x) 5.0
。当您执行此函数应用程序时,确实推断出 x 具有您显式编写的类型。
下面两个函数的区别在于它们采用不同的类型。这两个函数之间的相似之处在于它们对输入执行相同的操作,即它们只是将其返回。