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

I am 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.

+8
functional-programming f #
source share
2 answers

There is no difference in your example. If return types are limited, you begin to see 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 to 'T when 'T :> Control . Sample constraints are important for creating common functions for subtypes.

For example,

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

against.

 let create (f: _ -> #Control) = f() let c = create (fun () -> Control()) // works let tv = create (fun () -> TreeView()) // works 
+13
source share

When passing the value directly as an argument to the F # function, the compiler automatically raises the value (therefore, if the function accepts Control , you can assign it a TextBox value). Thus, if you use a flexible type as a parameter type, there is not much difference.

However, there is a difference if the function accepts, for example, a list of '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! 
+7
source share

All Articles