Erlang案例陈述

时间:2014-01-13 04:25:55

标签: erlang erlang-shell erl

我有以下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之后尝试了一个匿名变量,但它仍然不开心。

2 个答案:

答案 0 :(得分:8)

使用~p。的格式。这意味着 - 打印价值。因此,您必须指定要打印的值。

最后一行必须是

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

此外,io:格式化返回'确定'。因此,如果P不是x y或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.

答案 1 :(得分: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}同样有效。您需要选择最适合您情况的变体。