## Increase the readability of you source code by using the Pipe Forward operator

I really like the Pipe Forward operator in F#. This simple operator allows to write source code which matches a read direction from left to right.

Pipe Forward operator example

The following example shows the Pipe Forward operator in action. Let’s say you have to do some mathematical calculations. For example you want to calculate the square root of a value round it up to the next integer value and return the result as an integer. In this case you may write the following source code.

```let x = 9.5;
let y = Convert.ToInt32 (Math.Ceiling (Math.Sqrt x))
```

As you can see even this short line of code is not easy to read because the reading direction of the source code is from right to left which does not correspond with you preferred reading direction left to right.

In such cases the Pipe Forward operator may be used. This operator allows to pipe a parameter to a function. The piped parameter is used as the last parameter of the function. The following source code shows the previous example implemented by using the Pipe Forward operator.

```let x = 9.5;
let y = x |> Math.Sqrt |> Math.Ceiling |> Convert.ToInt32
```

Now the reading direction of the source code is from left to right. If you compare both examples you will see the increases readability of the second example.

Pipe Forward operator implementation

The Pipe Forward operator is implemented as a very simple function:

```let (|>) x f = f x
```

Therefore this operator isn’t a compiler trick or some syntactic sugar. It is a plain and simple but very useful function.

Pipe Backward operator

There exists a Pipe Backward operator too. This operator is defined as:

```let (<|) f x = f x
```

Therefore this operator allows to pipe a parameter to a function but in contrast to the Pipe Forward operator the parameter is written behind the function.

You may ask yourself whether this is useful because it will change to reading order back to right to left. But there are some cases where this operator may be used to increase the readability of code. For example it may reduce the need for parenthesis. The following example will show a possible use case for the Pipe Backward operator.

```printf "Result: %d" (2 + 2)
printf "Result: %d" <| 2 + 2
```

Summary

The Pipe Forward operator is one of the little treasures I really like in F# because it will provide a very effective and efficient possibility to increase the readability and of your source code.

Dieser Beitrag wurde unter .NET, F# abgelegt und mit , , verschlagwortet. Setze ein Lesezeichen auf den Permalink.