我有以下 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 之后尝试了一个匿名变量,但仍然不满意。
在您使用 ~p 的格式中。它的意思是——打印值。因此,您必须指定要打印的值。
case 的最后一行必须是
_ -> io:format("no match ~p~n",[P])
此外,io:format 返回“ok”。因此,如果 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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)