我知道有一个后管(<|)操作员,在其他几个SO答案中引用.但是当与前管相结合时(|>),这种方法效果不佳,这在链接中很常见.但是我正在寻找相关的选择.基本上是否有以下功能定义的内置版本?或者这是一个坏/危险的做法?
let inline (^%) f = f
let stuff =
[1;2;3]
|> Seq.filter ^% (>) 2
|> Seq.map ^% fun x -> x.ToString()
// compare to this, which doesn't compile (and would be hard to follow even if it did)
let stuff =
[1;2;3]
|> Seq.filter <| (>) 2
|> Seq.map <| fun x -> x.ToString()
Run Code Online (Sandbox Code Playgroud)
有一些Haskell功能,比如使用反引号的可选中缀,以及F#中没有的部分.这使得某些结构更加冗长.
通常,我只是像上面这样编写一系列函数:
let stuff =
[1;2;3]
|> Seq.filter (fun x -> x < 2)
|> Seq.map string
Run Code Online (Sandbox Code Playgroud)
在我看来,这更具可读性.例如,使用Seq.filter ^% (>) 2,我直观地将其视为"所有值大于2",但这不是它的作用:
> let inline (^%) f = f;;
val inline ( ^% ) : f:'a -> 'a
> let stuff =
[1;2;3]
|> Seq.filter ^% (>) 2
|> Seq.map ^% fun x -> x.ToString()
|> Seq.toList;;
val stuff : string list = ["1"]
Run Code Online (Sandbox Code Playgroud)
如果您让代码的读者对代码的作用存在疑问,那么您只会降低每个人的工作效率.使用Seq.filter (fun x -> x < 2)可能看起来更冗长,但对读者来说是明确的.