我可以在 Elixir 中连接字符串并使用管道运算符吗?

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

在 Elixir 中,您可以使用 <> 运算符连接字符串,就像在 "Hello" <> " " <> "World" 中一样。

您还可以使用管道运算符 |> 将函数链接在一起。

我正在尝试编写 Elixir 代码来格式化在线游戏的货币。

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

以上导致语法错误。我是否忽略了一个可以连接字符串的基本函数?我知道我可以自己定义一个,但如果我能避免的话,这似乎会在我的代码中造成不必要的混乱。

我意识到我可以完成同样的事情,只需像 to_string(Float.round(price/10000, 2)) <> "g" 那样将方法链接在一起,但是这种语法不那么好读,而且它使得在未来,如果我想在两者之间添加步骤。

Elixir 是否有使用管道运算符连接文本的方法,或者如果不自己定义方法就不可能吗?

是的,您可以传递函数的完整路径,在本例中为 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.

您可以使用 插值 而不是 连接 。比如你可以这样写,读起来还是可以的,而且简单,好修改:

def format_price(price) do
  price = (price / 10000) |> Float.round(2)
  "#{price}g"
end

回答您的问题

回答你的问题:

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

如@Dogbert 在 中所述,您可以使用 Kernel.<>/2

另一个解决方案是使用then/2

def format_price(price) do
  (price / 10000)
  |> Float.round(2)
  |> to_string()
  |> then(&"#{&1}g")
end

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