createTuple下面的函数可以无表情地表达吗?
let createTuple = fun v -> (v, v*2)
createTuple 2 |> printfn "%A" // (2,4)
Run Code Online (Sandbox Code Playgroud)
F#库没有提供许多用于以无点样式编写代码的函数(主要是因为它不是特别惯用的编写F#的方式),所以你不能createTuple使用核心库中的可用内容来编写函数.
如果你真的想这样做,你可以定义几个辅助组合器来处理元组:
/// Duplicates any given value & returns a tuple with two copies of it
let dup a = a, a
/// Transforms the first element using given function
let mapFst f (a, b) = (f a, b)
/// Transforms the second element (not needed here, but adding for symmetry)
let mapSnd f (a, b) = (a, f b)
Run Code Online (Sandbox Code Playgroud)
有了这些,您可以以无点的方式实现您的功能:
let createTuple = dup >> mapSnd ((*) 2)
Run Code Online (Sandbox Code Playgroud)
这和你的功能一样.我认为破解这里发生的事情要难得多,而且我永远不会真正编写代码,但这是另一个问题:-).