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

Tri*_*Gao 1 f#

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

Gus*_*Gus 5

简短的回答是否定的,原因在约翰链接的问题中进行了解释。

它将与方法重载一起工作,尽管这更像是一个 .NET 功能而不是 F# 特定的功能。

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"
Run Code Online (Sandbox Code Playgroud)

但是对于函数,没有干净的方法可以做到这一点,您可以找到一些技巧,例如:

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"
Run Code Online (Sandbox Code Playgroud)

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