3

我有以下 Erlang 代码,当我尝试编译它时,它给出如下警告,但这是有道理的。函数需要两个参数,但我需要匹配“其他所有内容”而不是 x、y 或 z。

-module(crop).
-export([fall_velocity/2]).

fall_velocity(P, D) when D >= 0 ->
case P of
x -> math:sqrt(2 * 9.8 * D);
y -> math:sqrt(2 * 1.6 * D);
z -> math:sqrt(2 * 3.71 * D);
(_)-> io:format("no match:~p~n")
end.

crop.erl:9: Warning: wrong number of arguments in format call. 

我在 io:format 之后尝试了一个匿名变量,但它仍然不开心。

4

2 回答 2

8

以您使用的格式 ~p. 它的意思是——打印价值。因此,您必须指定要打印的值。

案例的最后一行必须是

_ -> io:format("no match ~p~n",[P])

此外, io:format 返回“ok”。因此,如果 P 不是 xy 或 z,您的函数将返回 'ok' 而不是数值。我建议返回标记值以区分正确和错误返回。有点儿

fall_velocity(P, D) when D >= 0 ->
case P of
x -> {ok,math:sqrt(2 * 9.8 * D)};
y -> {ok,math:sqrt(2 * 1.6 * D)};
z -> {ok,math:sqrt(2 * 3.71 * D)};
Otherwise-> io:format("no match:~p~n",[Otherwise]),
            {error, "coordinate is not x y or z"}
end.
于 2014-01-13T05:23:49.783 回答
3

为了明确对另一个答案的评论,这就是我编写该函数的方式:

-module(crop).
-export([fall_velocity/2]).

fall_velocity(P, D) when D >= 0 ->
    case P of
        x -> math:sqrt(2 * 9.8 * D);
        y -> math:sqrt(2 * 1.6 * D);
        z -> math:sqrt(2 * 3.71 * D)
    end.

也就是说,不要在你的 case 表达式中处理不正确的参数。如果有人foo作为参数传递,您将收到错误{case_clause, foo}以及指向此函数及其调用者的堆栈跟踪。这也意味着这个函数不能因为使用不正确的参数调用而将不正确的值泄漏到代码的其余部分。

与其他答案一样返回{ok, Result} | {error, Error}同样有效。您需要选择最适合您情况的变体。

于 2014-01-13T10:28:30.977 回答