简体   繁体   中英

Using pipe with filter and map in elixir

I am attempting to filter out some values from a map in Elixir.

This:

params = %{"blah" => "blah", "vtha" => "blah"}
params 
  |>  Enum.filter fn {k, v} -> k == v end 
  |>  Enum.map(fn {k, v} -> {k, v} end)

Result in this Error: ** (FunctionClauseError) no function clause matching in Enumerable.Function.reduce/3

But both the filter and map operations work in isolation.

Enum.filter params, fn {k, v} -> k == v end 
Enum.map(params, fn {k, v} -> {k, v} end)

They don't work when piped.

I am sure I am missing something obvious.

EDIT On the master branch of Elixir, the compiler will warn if a function is piped into without parentheses if there are arguments.


You need explicit parenthesis for Enum.filter as the function call has a stronger precedence than the pipe operator.

params = %{"blah" => "blah", "vtha" => "blah"}
params 
  |>  Enum.filter(fn {k, v} -> k == v end)
  |>  Enum.map(fn {k, v} -> {k, v} end)

Please see Why Can't I Chain String.replace? for a more detailed explanation.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM