F#中灵活类型注释的目的是什么?

时间:2013-01-22 11:31:51

标签: .net f# functional-programming f#-3.0

我正在学习F#并且我不了解灵活类型的目的,或者更好,我不能理解写这个之间的区别:

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

并写下这个:

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

其中ControlSystem.Windows.Forms.Control类。

2 个答案:

答案 0 :(得分:15)

你的例子没有区别。如果返回类型受到限制,您就会开始看到差异:

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

请注意,#Control'T when 'T :> Control的快捷方式。 Type constraints对于为子类型创建通用函数很重要。

例如,

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

答案 1 :(得分:7)

当直接将值作为参数传递给F#函数时,编译器会自动向上转换值(因此,如果函数采用Control,则可以为其赋予TextBox值。因此,如果您使用灵活类型作为参数类型,则没有太大区别。

但是,如果函数需要,例如列表'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!