Erlang案例陈述

Tha*_*ela 2 erlang erl erlang-shell

我有以下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. 
Run Code Online (Sandbox Code Playgroud)

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

Odo*_*rus 8

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

最后一行必须是

_ -> io:format("no match ~p~n",[P])
Run Code Online (Sandbox Code Playgroud)

此外,io:格式返回'确定'.因此,如果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.
Run Code Online (Sandbox Code Playgroud)