我编写了一个名为 is_zero
的简单函数在 Erlang 中,它检查函数的参数是否为零。代码如下。
-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)它返回一条警告:variable "X" is unused
。
如果我运行is_zero(0).
尽管有警告,shell 仍会抛出异常错误,显示 undefined shell command is_zero/1
我做错了什么?
我想不出任何纠正措施,也找不到任何有帮助的建议。
最佳答案
Erlang 中的函数定义在 modules 内。为了区分不同模块中的函数,您需要在函数前添加模块名称。在这种情况下,您需要运行 match:is_zero(0)。
而不仅仅是 is_zero(0)。
。
为了避免警告说变量“X”未使用
,请使用下划线变量:
is_zero(_) ->
false.
请注意,即使未使用,变量名称也很有用,可以提高可读性。如果您想命名变量并仍然避免编译器警告,请在名称前添加下划线:
is_zero(_Num) ->
false.
关于erlang - Erlang 中的模式匹配会引发变量未被使用的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42702714/