Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 739
Kevin Avatar asked Jul 25 '16 04:07

Kevin


People also ask

Which operator can be used in string concatenation?

Operator + is used to concatenate strings, Example String s = “i ” + “like ” + “java”; String s contains “I like java”.

What does the pipe operator do in Elixir?

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 .


2 Answers

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

iex(1)> "foo" |> Kernel.<>("bar") "foobar" 
like image 50
Dogbert Avatar answered Oct 04 '22 11:10

Dogbert


My two cents

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 

Answering your question

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 
like image 39
ryanwinchester Avatar answered Oct 04 '22 09:10

ryanwinchester