方法链 vs |>管道操作员 [英] Method Chaining vs |> Pipe Operator

查看:16
本文介绍了方法链 vs |>管道操作员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下代码:

// Learn more about F# at http://fsharp.net
open System
open System.Linq
open Microsoft.FSharp.Collections

let a = [1; 2; 3; 4; 54; 9]

let c = a |> List.map(fun(x) -> x*3) |> List.filter(fun(x) -> x > 10)
let d = a.Select(fun(x) -> x*3).Where(fun(x) -> x > 10)

for i in c do
    Console.WriteLine(i)

for i in d do
    Console.WriteLine(i)

两者似乎都做同样的事情,但我看到的大多数 F# 示例都使用了 |> 管道运算符,而我更习惯于方法链接(a.l.a. C# Linq).后者也更短一些,尽管在一起更紧缩.目前我使用的是 C# Linq 语法,但这更多是习惯/惯性,而不是任何真正的设计决定.

Both seem to do the same thing, but most F# examples I see use the |> pipe operator, while I'm more used to method chaining (a.l.a. C# Linq). The latter is also somewhat shorter, albeit somewhat more crunched together. For now i'm using the C# Linq syntax, but that's more of habit/inertia rather than any real design decision.

是否有任何我应该了解的注意事项,或者它们是否基本相同?

Are there any considerations that I should know about, or are they basically identical?

另一个考虑因素是 Pipe 语法比 Linq 语法更嘈杂":我正在执行的操作(例如map")非常短且小写,而每个操作前面都带有这个巨大的|>列表"那个,除了让它更长之外,还会分散注意力,远离微小的、小写的方法名称.甚至 StackOverflow 的语法高亮显示错误(不相关)的东西.要么就是我不习惯.

The other consideration is that the Pipe syntax is significantly more "noisy" than the Linq syntax: the operation I am doing (e.g. "map") is really short and in lowercase, while each one is preceded by this Huge "|> List" that, apart from making it longer distracts the eye away from the tiny, lowercase method name. Even StackOverflow's syntax highlighter highlights the wrong (irrelevant) thing. Either that or I'm just not used to it.

推荐答案

流水线支持 F# 的从左到右的类型推断.a.GroupBy 要求 a 的类型已知为 seq<_>,而 a |>Seq.groupBy 本身将 a 推断为 seq<_>.以下功能:

Pipelining supports F#'s left-to-right type inference. a.GroupBy requires that the type of a is already known to be seq<_>, whereas a |> Seq.groupBy itself infers a to be seq<_>. The following function:

let increment items = items |> Seq.map (fun i -> i + 1)

需要使用 LINQ 编写类型注释:

requires a type annotation to be written using LINQ:

let increment (items:seq<_>) = items.Select(fun x -> x + 1)

当您习惯了函数式风格时,您会找到使代码更简洁的方法.比如前面的函数可以简写为:

As you get comfortable with the functional style you'll find ways to make your code more concise. For example, the previous function can be shortened to:

let increment = Seq.map ((+) 1)

这篇关于方法链 vs |>管道操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆