Erlang 中的模式匹配会抛出变量未使用的警告

Pattern matching in Erlang throws a warning of a variable being unused

我在 Erlang 中编写了一个名为 is_zero 的简单函数,它检查函数的参数是否为零。代码如下

-module(match).

-export([is_zero/1]).

% defining a function named is_zero

% this is a function with two clauses

% these clauses are matched sequentially

is_zero(0) ->
    true;
is_zero(X) ->
    false.

当我尝试使用 c(match).(该文件也被命名为 match.erl)编译代码时,它 returns 警告说 variable "X" is unused

如果我 运行 is_zero(0). 尽管警告, shell 抛出一个异常错误说 undefined shell command is_zero/1

我做错了什么?

我想不出任何纠正方法,也找不到任何有用的建议。

Erlang 中的函数定义在 modules 中。为了区分来自不同模块的功能,您需要将模块名称添加到功能之前。在这种情况下,您需要 运行 match:is_zero(0). 而不是 is_zero(0)..

为了避免警告说 variable "X" is unused,使用下划线变量:

is_zero(_) ->
    false.

请注意,变量名即使未使用也很有用,可提高可读性。如果您想命名变量并仍然避免编译器警告,请在名称前加上下划线:

is_zero(_Num) ->
    false.