参数多态性与亚型多态性F# [英] Parametric Polymorphism vs Subtype polymorphism F#

查看:137
本文介绍了参数多态性与亚型多态性F#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个F#类型签名之间有什么区别(如果有的话)?

  UseTheStream<'a when'a: >流> :'a  - >单位

  UseTheStream:(stream:Stream) - >单位

在这种情况下,它们的意思是否相同?



msdn指出以下关于(:>)类型约束

  type-parameter:> type  - 提供的类型必须等于或从指定的类型派生,或者如果类型是接口,则提供的类型必须实现该接口。 

这表示这两个签名说的是相同的东西。所以在功能上,它们有什么不同?

解决方案

最重要的是,第一个功能是通用的。在你的例子中,它可能没有关系,但如果类型参数影响函数的返回类型,它可以:

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

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

s1 的MemoryStream s2 Stream



注意: #T 简写为'U when'U:> T


What is the difference (if any) between these two F# type signatures?

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

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:

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

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

s1 is MemoryStream. s2 is Stream.

NOTE: #T is shorthand for 'U when 'U :> T.

这篇关于参数多态性与亚型多态性F#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆