Types f中用户定义类型的混淆#

Types f中用户定义类型的混淆#,types,f#,Types,F#,对于int和string等内置类型,在函数中注释它们的方法如下: let testFunction (x:int) = x * x let test (a:NewType) = match a with | NewType x -> x * 2 但是对于用户定义的类型,使用它们的方式是不同的。如下图所示: type NewType = NewType of int let test (NewType a)= a * 2 但是,如果我按以下方式进行设置,intepre

对于int和string等内置类型,在函数中注释它们的方法如下:

let testFunction (x:int) = x * x
let test (a:NewType) =
    match a with
    | NewType x -> x * 2
但是对于用户定义的类型,使用它们的方式是不同的。如下图所示:

type NewType = NewType of int

let test (NewType a)= a * 2
但是,如果我按以下方式进行设置,intepreter会给出不匹配类型错误(int vs NewType):


为什么会这样?

这是一个类型注释:

let testFunction (x:int) = x * x
let test (a:NewType) = a * 2
但话说回来:

let test (NewType a)= a * 2
这不是类型批注。通过模式匹配将其称为分解。模式匹配也可以应用于函数参数,如示例中所示。它所做的是展开包含在
NewType
中的
int
值,并将其绑定到
a
值。这就是为什么可以进行乘法,因为它是在
int
值上进行的,而不是在
NewType上进行的

最后一行也是类型注释:

let testFunction (x:int) = x * x
let test (a:NewType) = a * 2

它不起作用,因为乘法在默认情况下被推断为
int
,并且注释指示
a
类型为
NewType
,这就是为什么您会收到此错误消息。您必须像打开测试(a:NewType)=a*2一样打开它,因为您混淆了模式匹配和类型注释。第二个示例使用了正确的类型注释:

let test (a:NewType) = a * 2
不幸的是,这意味着您无法在没有模式匹配提取的情况下访问类型构造函数的int参数,如下所示:

let testFunction (x:int) = x * x
let test (a:NewType) =
    match a with
    | NewType x -> x * 2
对您有效的第一种情况不是使用类型注释,而是将模式匹配作为参数的一部分,以便您尝试访问的值 已指定名称,不需要进一步的模式匹配。如果你的类型有不止一个这样的模式

type NewType = NewType of int
             | OtherType of float
如果您试图第一次使用模式而不是类型注释编写代码,您将看到一条警告,指出您的模式匹配不完整:

> let testcode (NewType a) = a * 2;;                  

  let testcode (NewType a) = a * 2;;
  --------------^^^^^^^^^

warning FS0025: Incomplete pattern matches on this expression. For example, 
the value 'OtherType (_)' may indicate a case not covered by the pattern(s).

哦,是的。谢谢你指出这一点。当我看到回复中的签名时,这是有道理的。它返回type
NewType=|NewType of int
。非常感谢。