Erlang案例声明 [英] Erlang case statement
问题描述
我有以下Erlang代码,它正在给出警告如下,当我尝试编译,但这是有道理的。功能需要两个参数,但是我需要拍照匹配所有其他,而不是x,y或z。
I have the following Erlang code and it is giving the warning as follows, when i try to compile it, but that make sense. function need two arguments, but i need to patten match "everything else" rather x, y or 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:格式之后尝试一个匿名变量,但仍然不高兴。 >
I was trying an anonymous variable after io:format, but still it is not happy.
推荐答案
以您使用的格式〜p。这意味着 - 打印值。所以你必须指定要打印的值。
In the format you use ~p. It means -- print value. So you must specify what value to print.
最后一行必须是
_ -> io:format("no match ~p~n",[P])
此外,io:格式returms'ok'。所以如果P不是x y或z,你的函数将返回'ok'而不是数值。我建议返回标记值以分离正确和错误的返回。当D> = 0时,
Besides, io:format returms 'ok'. So if P is not x y or z, your function will return 'ok' instead of numeric value. I would suggest to return tagged value to separate correct and error returns. Kind of
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.
这篇关于Erlang案例声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!