F#中是否有功能专业化,为什么不呢?

时间:2013-09-28 03:46:29

标签: f#

有一种方法可以根据参数的类型在C ++中实现specific函数的实现。在F#中有类似的东西吗?

1 个答案:

答案 0 :(得分:4)

简短的回答是否定的,原因在John关联的问题中解释。

它将与方法重载一起使用,尽管这是一个比F#特定的.NET功能。

type T = T with
    static member test (x:'a   list) = "Generic version"  
    static member test (x:int  list) = "Specialized for int"  
    static member test (x:char list) = "Specialized for char"  

> T.test ["0"] ;;
val it : string = "Generic version"
> T.test [0] ;;
val it : string = "Specialized for int"

但是有了功能,没有干净的方法可以做到这一点,你可以找到一些技巧,如:

type T = T with
    static member ($) (a:T, x:'a   list) = "Generic version"  
    static member ($) (a:T, x:int  list) = "Specialized for int"  
    static member ($) (a:T, x:char list) = "Specialized for char"  

let inline f a = T $ a : string

> f ["0"] ;;
val it : string = "Generic version"
> f [0] ;;
val it : string = "Specialized for int"

但这是非常有限的,它创建了一个带有静态约束的内联函数,在当前版本的F#中并不总是能够反映相同的重载分辨率,因此我不认为你可以采用这种方法。