Understanding functional pipes

In Julia, there is a pipe operator that can be used to pass data from one function to another. The concept is very simple. First, let's take a look at some examples.

In the previous section, we developed a fetch_top_stories function that's used to retrieve the current top stories from Hacker News. The return value is a JSON3.Array object that looks like an array of integers. Let's say we want to find the first story ID from the array. To do this, we can create a pipe operation, as follows:

The pipe operator |> is actually defined as a regular function in Julia, just like how + is defined as a function. Note that the preceding code is syntactically equivalent to the following:

In addition, we can use multiple pipe operators in an expression. For example, we can retrieve the details of the first story by appending the fetch_story function at the end of the pipe:

Because the data naturally flows from left to right, this is called a functional pipe pattern. This can be seen in the following diagram:

Note that every function that follows the piping operator must accept a single argument. In the preceding example, we can see the following:

  • The first function takes an array and returns the first element.
  • The fetch_story function takes an integer of the story ID and returns a Story object.

This is a very important point, so let me say this once again  a functional pipe only feeds data to single-argument functions

We will learn about how to deal with this constraint later. For now, we will talk about a similar pattern where the syntax is written in reverse compared to functional pipes. This concept is called composability, and is a design technique that leads to highly reusable code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.19.27.178