首页 > 解决方案 > 为什么 Enum.filter 不能与字典参数一起使用?

问题描述

我正在使用过滤列表Enum.filter/2

我已将代码简化为隔离正在发生的事情的基本要素,但我不明白哪里出了问题。

这是代码:

defmodule Servy.Reducer do
   alias Servy.Wildthings

   def index(%{} = bear_filter) do
      Wildthings.list_bears()
      |> Enum.filter(
         fn(bear) ->
          IO.inspect(bear_filter)
          case bear do 
             bear_filter -> true
                       _ -> false
               end
            end)
   end  
end

当我编译时,我会收到这些警告,如果属实,这将解释问题。我既不明白为什么bear_filter未使用也不明白为什么该_子句无法访问。

warning: variable "bear_filter" is unused (if the variable is not meant to be used, prefix it with an underscore)
  lib/servy/reducer.ex:10: Servy.Reducer.index/1

warning: this clause cannot match because a previous clause at line 10 always matches
  lib/servy/reducer.ex:11

标签: elixir

解决方案


Elixir 允许对变量进行反弹。所以在你的 case 表达式中,你有 branch bear_filter -> true。这实际上是在创建一个新变量并始终匹配(这就是为什么它说它未使用以及第二个分支无法访问的原因)。如果要与传递给函数的 相匹配bear_filter,则需要添加pin 运算符。所以你会将该行更改为^bear_filter -> true.


推荐阅读