Can I concatenate strings in Elixir and use the pipe operator?

Kevin picture Kevin · Jul 25, 2016 · Viewed 7.1k times · Source

In Elixir, you can concatenate strings with the <> operator, like in "Hello" <> " " <> "World".

You can also use the pipe operator |> to chain functions together.

I'm trying to write the Elixir code to format the currency for an online game.

def format_price(price) do
  price/10000
  |> Float.round(2)
  |> to_string
  |> <> "g"
end

The above results in a syntax error. Am I overlooking a basic function that can concatenate strings? I know I can define one myself, but that seems like creating unnecessary clutter in my code if I can avoid it.

I realize I can accomplish the same thing, by simply chaining the methods together like to_string(Float.round(price/10000, 2)) <> "g", but this syntax isn't as nice to read, and it makes it more difficult to extend the method in the future, if I want to add steps in between.

Does Elixir have ways to concatenate text using the pipe operator, or is that not possible without defining the method yourself?

Answer

Dogbert picture Dogbert · Jul 25, 2016

Yes, you can, by passing the full path to the function, which in this case is Kernel.<>:

iex(1)> "foo" |> Kernel.<>("bar")
"foobar"