接受多种类型的函数

A function that accepts multiple types

我是 f# 的新手,但我想知道是否可以制作一个接受多种类型变量的函数。

let add x y = x + y
let integer = add 1 2
let word = add "He" "llo"

一旦一个函数使用了一种类型的变量,它就不能接受另一种。

您需要阅读有关 statically resolved type parameters and inline functions 的内容。它允许创建可以采用支持操作 and/or 的任何类型的函数。所以你的 add 函数应该这样定义:

let inline add x y = x + y

不要过度使用内联函数,因为它们的代码在调用站点内联,可能会增加程序集大小,但可能会提高性能(测试每个案例,不要做出预测!)。此外,内联函数仅受 F# 编译器支持,可能不适用于其他语言(在设计库时很重要)。

Example SRTP 魔法:

let inline (|Parsed|_|) (str: string) =
    let mutable value = Unchecked.defaultof<_>
    let parsed = ( ^a : (static member TryParse : string * byref< ^a> -> bool) (str, &value))
    if parsed then
        Some value
    else
        None

match "123.3" with
| Parsed 123 -> printfn "int 123"
| Parsed 123.4m -> printfn "decimal 123.4"
| Parsed 123.3 -> printfn "double 123.3"
// | Parsed "123.3" -> printfn "string 123.3" // compile error because string don't have TryParse static member
| s -> printfn "unmatched %s" s