Ben Campbell
Ben Campbell

Reputation: 4668

How do I map any given function over a list of values?

I am splitting a string on a character and would like to trim the all the items in the resulting split. I would expect the following to work as String.trim/1 exists:

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 receive an UndefinedFunctionError indicating the function String.trim/0 does not exist. What I want is easily accomplished 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 Enum.map/2 require an anonymous function as a second parameter? Is it possible to give my desired function as a parameter?

Upvotes: 4

Views: 942

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Though the answer by @theanh-le is definitely correct and perfectly answers your question, you don’t need a String#trim/1 here at all. String#split/3 accepts a regular expression:

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

Upvotes: 3

TheAnh
TheAnh

Reputation: 2813

You need to use & operator. Capture operator

Try this:

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

Upvotes: 7

Related Questions