Elixir has the possibility to pipe input into a function, which makes code more readable very often.
For example something like this
sentence |> String.split(@wordSplitter, trim: true)
which pipes the String sentence
into the first argument of String.split
.
Now consider I would also like to pipe the second argument into String.split
. Is there a possibility to do that in Elixir? I mean something like this:
sentence, @wordSplitter |> String.split(trim: true)
Thanks!
As @Dogbert pointed out, this is impossible out of the box. The helper is pretty straightforward, though:
defmodule MultiApplier do
def pipe(params, mod, fun, args \\ []) do
apply(mod, fun, List.foldr(params, args, &List.insert_at(&2, 0, &1)))
end
end
iex> ["a b c", " "]
...> |> MultiApplier.pipe(String, :split, [[trim: true]])
#⇒ ["a", "b", "c"]
iex> ["a b c", " ", [trim: true]]
...> |> MultiApplier.pipe(String, :split, [])
#⇒ ["a", "b", "c"]
iex> ["a b c"]
...> |> MultiApplier.pipe(String, :split, [" ", [trim: true]])
#⇒ ["a", "b", "c"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.