Mark Pearl
Mark Pearl

Reputation: 7653

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

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

Upvotes: 9

Views: 644

Answers (4)

Brian
Brian

Reputation: 118865

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.

Upvotes: 2

James Moore
James Moore

Reputation: 9026

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

Upvotes: 3

Tomas Petricek
Tomas Petricek

Reputation: 243051

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#).

Upvotes: 8

LBushkin
LBushkin

Reputation: 131676

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.

Upvotes: 12

Related Questions