What is the purpose of flexible type annotation in F#?

走远了吗. 提交于 2019-12-10 12:57:15

问题


I'm studying F# and I don't understand the purpose of flexible types, or better, I can't understand the difference between writing this:

set TextOfControl (c : Control) s = c.Text <- s

and writing this:

set TextOfControl (c : 'T when 'T :> Control) s = c.Text <- s

where Control is the System.Windows.Forms.Control class.


回答1:


There is no difference in your example. If return types are constrained, you start seeing the difference:

let setText (c: Control) s = c.Text <- s; c
let setTextGeneric (c: #Control) s = c.Text <- s; c

let c = setText (TreeView()) "" // return a Control object
let tv = setTextGeneric (TreeView()) "" // return a TreeView object

Note that #Control is a shortcut of 'T when 'T :> Control. Type constraints are important to create generic functions for subtypes.

For example,

let create (f: _ -> Control) = f()

let c = create (fun () -> Control()) // works
let tv = create (fun () -> TreeView()) // fails

vs.

let create (f: _ -> #Control) = f()

let c = create (fun () -> Control()) // works
let tv = create (fun () -> TreeView()) // works



回答2:


When passing a value directly as an argument to an F# function, the compiler autoamtically upcasts the value (so if the function takes Control, you can give it TextBox value). So, if you use a flexible type as a type of parameter, there is not a big difference.

However, there is a difference if the function takes, for example a list 'T list:

// Takes a list of any subtype of object (using flexible type)
let test1<'T when 'T :> obj> (items:'T list) =
  items |> List.iter (printfn "%A")

// Takse a list, which has to be _exactly_ a list of objects
let test2 (items:obj list) =
  items |> List.iter (printfn "%A")

// Create a list of System.Random values (System.Random list)
let l = [new System.Random()]
test1 l // This works because System.Random is subtype of obj
test2 l // This does not work, because the argument has wrong type!


来源:https://stackoverflow.com/questions/14457571/what-is-the-purpose-of-flexible-type-annotation-in-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!