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?
Operator + is used to concatenate strings, Example String s = “i ” + “like ” + “java”; String s contains “I like java”.
The pipe operator is the main operator for function composition in Elixir. It takes the result of the expression before it and passes it as the first argument of the following expression. Pipes replace nested function calls like foo(bar(baz)) with foo |> bar |> baz .
Yes, you can, by passing the full path to the function, which in this case is Kernel.<>
:
iex(1)> "foo" |> Kernel.<>("bar") "foobar"
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.
You could use interpolation instead of concatenation. For example, you could do it like this and it's still okay to read, and simple, so easy to modify:
def format_price(price) do price = (price / 10000) |> Float.round(2) "#{price}g" end
To answer your question:
Does Elixir have ways to concatenate text using the pipe operator, or is that not possible without defining the method yourself?
As mentioned in the other answer by @Dogbert, you can use Kernel.<>/2
Another solution is to use then/2
.
def format_price(price) do (price / 10000) |> Float.round(2) |> to_string() |> then(&"#{&1}g") end
or
def format_price(price) do (price / 10000) |> Float.round(2) |> to_string() |> then(&(&1 <> "g")) end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With