Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 962
Fr.Usai Avatar asked Jan 22 '13 11:01

Fr.Usai


1 Answers

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
like image 135
pad Avatar answered Nov 16 '22 04:11

pad