2014-01-13 146 views
2

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

-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格式,但它仍然不开心。

回答

8

以您使用〜p的格式。这意味着 - 打印价值。所以你必须指定要打印的值。案例

最后一行必须

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

此外,IO:格式returms 'OK'。所以如果P不是x或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

我会抛出一个异常,或者甚至不检查x,y,z以外的其他东西。 Erlang难以理解,不需要过度。 – Berzemus

+0

没错。但是如果不检查,你可以在比调用函数晚得多的地方发生错误。 {ok,R} = fall_velocity(A,B)可能会提前指出错误。 –

+0

http://www.erlang.se/doc/programming_rules.shtml#REF32551 –

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. 

也就是说,处理不正确的说法,你的情况表达。如果有人通过foo作为参数,您将收到错误{case_clause, foo}以及指向此函数其调用者的堆栈跟踪。这也意味着该函数不能将不正确的值泄漏到代码的其余部分中,因为被调用的参数不正确。

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