elixir - 为什么 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 允许对变量进行反弹。所以在你的 case 表达式中,你有 branch bear_filter -> true
。这实际上是在创建一个新变量并始终匹配(这就是为什么它说它未使用以及第二个分支无法访问的原因)。如果要与传递给函数的 相匹配bear_filter
,则需要添加pin 运算符。所以你会将该行更改为^bear_filter -> true
.
推荐阅读
- npm - 安装vue-cli时如何修复错误
- python-3.x - 错误:找不到满足要求 tensorflow 的版本(来自版本:无)
- c# - .net Core 3.0 中的 Aes 加密“指定的密钥不是此算法的有效大小。”
- android - 应用程序在 IllegalArgumentException 后被杀死
- mysql - 无法在 ubuntu 19.04 上安装 libzip4
- copy - 如何使用工作表中的下一行以 15-16 的间隔编写代码以复制、粘贴、自上而下?
- node.js - 使用 child_process 模块执行文件时了解 child_process 模块和 exec 功能
- javascript - 同步的 Highchart 数据加载问题
- php - 从输入创建数组?
- javascript - Javascript 控制台不打印返回