How to match any function over a list of values?

I split the string into a character and would like to trim all the items as a result of the split. I expect the following to work as it String.trim/1exists:

iex> "My delimited ! string of doom" |> String.split("!") |> Enum.map(String.trim)
** (UndefinedFunctionError) function String.trim/0 is undefined or private. Did you mean one of:

  * trim/1
  * trim/2

(elixir) String.trim()

I get UndefinedFunctionErrorindicating that the function String.trim/0does not exist. What I want is easy to do with an anonymous function passed to Enum.map:

iex> "My delimited ! string of doom" |> String.split("!") |> Enum.map(fn (word) -> String.trim(word) end)
["My delimited", "string of doom"]

Does it use an Enum.map/2anonymous function as a second parameter? Is it possible to specify the desired function as a parameter?

+4
source share
2 answers

You need to use & operator. Capture operator

Try the following:

iex()> "my delimited ! string of doom" |> String.split("!") |> Enum.map(&String.trim/1)
["my delimited", "string of doom"]
+6
source

by @theanh-le , String#trim/1. String#split/3 :

iex(1)> "delimited ! string of doom" |> String.split(~r{\s*!\s*})
["delimited", "string of doom"]
+3

Source: https://habr.com/ru/post/1654410/


All Articles