The
|>
operator appears in many languages, mostly in the functional world. F# has essentially the exact same operator, as does OCaml. Elixir has a slightly fancier version (which we considered but ultimately decided against for now)
What is fancier about the Elixir one than the F#/OCaml one?
If I’m reading that page correctly, the right-hand side only allows for functions expecting a single argument whereas in Elixir the left-hand side becomes the value of the first argument on the right-hand side. My understanding comes from this line in the page linked:
The pipe operator, spelled
|>
, is deceptively simple. It takes the value on its left side and passes it as the single argument to a function (or in PHP’s case,callable
) on its right side
All of their examples seem to support this:
$string = 'something GoesHERE';
$newString = match ($format) {
'snake_case' => $string
|> splitString(...)
|> fn($x) => implode('_', $x)
|> strtolower(...),
'lowerCamel' => $string
|> splitString(...),
|> fn($x) => array_map(ucfirst(...), $x)
|> fn($x) => implode('', $x)
|> lcfirst(...),
// Other case options here.
};
There’s some syntax in that example I’m not familiar with (last time I did any serious PHP was in 2007), but my guess is that would be the difference.
Ocaml and F# have currying, so they don’t need to support more than 1-arity. Elixir has established a convention of treating the first argument as the “subject”, so piping into the first argument makes sense. In PHP’s case, there is neither currying, nor established convention for argument order. I think piping will be not be as elegant here.
Maybe they need something like we have in Arrows — arrows v0.2.1
# Standard first position pipe
2 |> Integer.to_string()
"2"
# Using ellipsis to place the piped value in a non-first position
3 |> String.pad_leading("2", ..., "0")
"002"
While on the topic of PHP there was a nice article about it just yesterday on Devtalk..
As much as I was never a fan of the syntax, it’s hard to deny that PHP sites can run well without issue for a decent period - I still manage some forums (running on PHP) that haven’t been updated in 15 years!
I still use it for small server-side interactions (though not for anything that has survived). It’s still the obvious choice for that that kind of thing, but lordy can I never get used to $
.
It’d be nice if Elixir core had all the arrows
functionality baked in
This is a dead horse that has been thoroughly beaten several times over. It’s never going to happen, but there are several options if you really want it.