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

查看:130
本文介绍了方法链接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#示例我看到使用|>管道操作符,而我更习惯于方法链接(ala 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?

编辑:
另一个考虑因素是管道语法比Linq语法显着更嘈杂:我的操作做(例如地图)真的很短,小写,而每个都在这个巨大的|>列表之前,除了使它更长的时间分散注意力,远离这个小小的方法名称。即使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 |&gt;管道操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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