在 F# 中,你会遇到这样的事情:
let p = Earth().GetCountry1().GetPopulation()
Run Code Online (Sandbox Code Playgroud)
有时我发现自己想要将参数与函数分开,就像在 F# 中通常所做的那样:
let p = ((Earth ()).GetCountry1 ()).GetPopulation ()
Run Code Online (Sandbox Code Playgroud)
这需要很多括号。是否有一个函数,或者有人可以想到一个函数,它可以用来代替点运算符,这有助于以更优雅的方式维护函数和参数之间的空间——像这样?
let dot method arg obj = obj.method arg
let p = Earth () |> dot GetCountry1 () |> dot GetPopulation ()
Run Code Online (Sandbox Code Playgroud)
(我的dot导致编译器错误。)
原始代码是完全惯用的 F#。没有必要改变它。
但是,有时您有一个 F# 函数管道,您需要在其中调用一个方法。最简洁的方法是使用 lambda:
aValue
|> aFunction parameter
|> anotherFunction
|> fun x -> x.Method()
|> oneLastFunction
Run Code Online (Sandbox Code Playgroud)
您尝试编写的函数在静态类型语言中是不可能的。这需要作为语言功能添加,或者您可以简单地使用 lambda,如上所示。
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |