我想实现一个可以接受1或2个参数的F#函数.我想使用这样的函数:
let foo = ...
foo "a"
foo "a" "b"
Run Code Online (Sandbox Code Playgroud)
两个参数都可以是相同的类型.我阅读了关于匹配模式,活动模式的页面,但找不到一个适合我的.
我相信这是由于一些潜在的.Net功能,但我认为你必须使用一个带有重载方法的类 - 类似于
type t() =
static member foo a = "one arg"
static member foo (a,b) = "two args"
Run Code Online (Sandbox Code Playgroud)
在类型成员上,您可以使用可选的参数:
type Helper private () =
static member foo (input1, ?input2) =
let input2 = defaultArg input2 "b"
input1, input2
Run Code Online (Sandbox Code Playgroud)
要调用此方法:
Helper.foo("a")
Helper.foo("a", "b")
Run Code Online (Sandbox Code Playgroud)
这就是你要追求的吗?
不幸的是,你不能在函数上使用可选的参数.
除了其他答案之外,您还可以通过部分应用和柯里化来完成您想要的操作。像这样:
let foo a b =
a + b
let foo2 a =
foo 1 a;;
Run Code Online (Sandbox Code Playgroud)
显然,您希望将 foo2 中对 foo 的调用中的第一个参数修复为您想要的任何默认值。
| 归档时间: |
|
| 查看次数: |
730 次 |
| 最近记录: |