Method Chaining vs |> Pipe Operator

后端 未结 5 1865
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-10 00:54

So I have the following code:

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


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-10 01:39

    To my understanding, the F# |> operator was introduced to make sequence operations look like LINQ queries, or better to make it look similar to C# extension method chaining. List.map and filter, in fact, are functions in a "functional" way: get a sequence and a f as input, return a sequence. Without pipe, the F# variant will be

    filter(fun(x) -> x > 10, map(fun(x) -> x*3, a))
    

    Notice that visually the order of the functions is reversed (application is still in the same order) : with |> they look more "natural", or better, they look more similar to the C# variant. C# achieves the same goal through extension methods: remember that the C# one is actually

    Enumerable.Where(Enumerable.Select(a, f1), f2)
    

    Enumerable.Select is a function where the first parameter is a "this IEnumerable", which is used by the compiler to transform it to a.Select... In the end, they are language facilities (realized through a compiler transformations in C#, and using operators and partial application in F#) to make nested function calls look more like a chain of transformations.

提交回复
热议问题