Pipe operator injects the first argument

The |> operator takes the result of the expression on its left and injects it as the first parameter of the function call to its right.

The Regex.replace function signature is this: run(regex, string, options \\ [])
The first argument is the regex.

Then how is it possible the following code to work without error
iex(115)> "cats like catnip" |> String.replace(~r/cat/, "dog") "dogs like dognip" iex(116)>
In the last example it seems that the pipe operator injects the second argument of the function.

1 Like

I do not get your question…

The typespec for Regex.replace/4 is replace(Regex.t, String.t, String.t | (... -> String.t), [term]) :: String.t, which has nothing to do with Regex.run/3.

The typespec for String.replace/4 is replace(String.t, pattern | Regex.t, String.t, keyword) :: String.t, and this is what you actually used in iex.

4 Likes

String.replace/3 is not the same as Regex.replace/3.
While String.replace/3 takes a string first, Regex.replace/3 takes a regular expression instead.

Take a look at the differences in the documentation of the two functions:
https://hexdocs.pm/elixir/String.html#replace/4
https://hexdocs.pm/elixir/Regex.html#replace/4

4 Likes

Oops! Obviously, it was my blunder.
String.replace/4 is a different function than Regex.replace/4.

However, while I was searching for an answer I bump upon this suggestion https://twitter.com/joeerl/status/340707833815388160

The numbered pipe has been discussed before, I do consider it as unreadable.

But there is param_pipe available on hex. Announcement and discussion is available on the forum as well:

1 Like

Haha, I am just too busy to do any upgrades currently.