在尝试编译 Elixir 模块(使用 Elixir 1.3.2 和 Erlang R19)时,我收到了一个相当奇怪的警告。代码来自《Elixir 简介》一书:
defmodule Drop do
def fall_velocity(distance) do
:math.sqrt(2 * 9.8 * distance)
end
def fall_velocity(distance, gravity \\ 9.8) do
:math.sqrt(2 * gravity * distance)
end
end
当我编译它时,shell 会说:
warning: this clause cannot match because a previous clause at line 2 always matches
drop.ex:6
第 6 行是第二个函数定义,第 2 行是第一个函数定义。
但是,当我使用该代码时,它工作正常:
iex(12)> Drop.fall_velocity(20)
19.79898987322333
iex(13)> Drop.fall_velocity(20, 1.6)
8.0
那么,该警告的含义是什么?
最佳答案
问题是 deffall_velocity(distance,gravity\\9.8) do
将定义 2 个函数,其中一个函数的数量为 1,它只会掉落重力设置为 9.8 的 arity 2 版本,还有一个函数arity 2。在这种情况下,您根本不需要第一个子句。第二个默认情况下将重力设置为 9.8,您将得到与 arity 1 相同的答案。
defmodule Drop do
def fall_velocity(distance, gravity \\ 9.8) do
:math.sqrt(2 * gravity * distance)
end
end
关于elixir - 编译模块时的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38844191/