简体   繁体   English

参数多态性与亚型多态性F#

[英]Parametric Polymorphism vs Subtype polymorphism F#

What is the difference (if any) between these two F# type signatures? 这两个F#类型签名之间有什么区别(如果有的话)?

UseTheStream<'a when 'a :> Stream> : 'a -> unit

and

UseTheStream : (stream : Stream) -> unit

Do they mean the same thing in this case? 在这种情况下,它们的意思是一样的吗?

msdn says the following about the (:>) Type Constraint msdn说出以下关于(:>)类型约束的内容

type-parameter :> type --   The provided type must be equal to or derived from the type      specified, or, if the type is an interface, the provided type must implement the interface.

This would indicate that the two signatures are saying the same thing. 这表明两个签名正在说同样的话。 So Functionally, how are they different? 从功能上来说,它们有何不同?

They are different. 他们是不同的。 Most importantly, the first function is generic. 最重要的是,第一个功能是通用的。 In your example it probably doesn't matter, but if the type parameter affects the function's return type, it does: 在您的示例中,它可能无关紧要,但如果type参数影响函数的返回类型,它会:

let UseTheStream (stream: #Stream) = stream
let UseTheStreamStrict (stream: Stream) = stream

let s1 = new MemoryStream() |> UseTheStream
let s2 = new MemoryStream() |> UseTheStreamStrict

s1 is MemoryStream . s1MemoryStream s2 is Stream . s2Stream

NOTE: #T is shorthand for 'U when 'U :> T . 注意: #T'U when 'U :> T简写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM