What is the name of |> in F# and what does it do?

我们两清 提交于 2019-12-19 05:37:48

问题


A real F# noob question, but what is |> called and what does it do?


回答1:


It's called the forward pipe operator. It pipes the result of one function to another.

The Forward pipe operator is simply defined as:

let (|>) x f = f x

And has a type signature:

'a -> ('a -> 'b) -> 'b

Which resolves to: given a generic type 'a, and a function which takes an 'a and returns a 'b, then return the application of the function on the input.

You can read more detail about how it works in an article here.




回答2:


I usually refer to |> as the pipelining operator, but I'm not sure whether the official name is pipe operator or pipelining operator (though it probably doesn't really matter as the names are similar enough to avoid confusion :-)).

@LBushkin already gave a great answer, so I'll just add a couple of observations that may be also interesting. Obviously, the pipelining operator got it's name because it can be used for creating a pipeline that processes some data in several steps. The typical use is when working with lists:

[0 .. 10] 
  |> List.filter (fun n -> n % 3 = 0) // Get numbers divisible by three
  |> List.map (fun n -> n * n)        // Calculate squared of such numbers

This gives the result [0; 9; 36; 81]. Also, the operator is left-associative which means that the expression input |> f |> g is interpreted as (input |> f) |> g, which makes it possible to sequence multiple operations using |>.

Finally, I find it quite interesting that pipelining operaor in many cases corresponds to method chaining from object-oriented langauges. For example, the previous list processing example would look like this in C#:

Enumerable.Range(0, 10) 
  .Where(n => n % 3 == 0)    // Get numbers divisible by three
  .Select(n => n * n)        // Calculate squared of such numbers

This may give you some idea about when the operator can be used if you're comming fromt the object-oriented background (although it is used in many other situations in F#).




回答3:


As far as F# itself is concerned, the name is op_PipeRight (although no human would call it that). I pronounce it "pipe", like the unix shell pipe.

The spec is useful for figuring out these kinds of things. Section 4.1 has the operator names.

http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec.html




回答4:


Don't forget to check out the library reference docs:

http://msdn.microsoft.com/en-us/library/ee353754(v=VS.100).aspx

which list the operators.



来源:https://stackoverflow.com/questions/2630940/what-is-the-name-of-in-f-and-what-does-it-do

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!