下面的 Erlang 函数有时甚至会导致 badarith 错误
当 Lat 和 Distance 的值为浮点值时
我不知道ct_expand:term 做了什么,但您可以轻松测试add_distance_lat() 在给定两个浮点数作为参数时不会导致badarith 错误。我从以下代码中删除了ct_expand:term:
-module(my).
-compile(export_all).
-define(EARTH_RADIUS, 6372800).
-define(PI, math:pi()).
-define(RAD_FACTOR, ?PI / 180).
test(0) -> ok;
test(N) ->
X = rand:uniform() * 1000,
Y = rand:uniform() * 10000,
io:format("X=~w, Y=~w~n", [X, Y]),
ok = add_distance_lat(X, Y),
test(N-1).
add_distance_lat(Lat, Distance) ->
try Lat + ((Distance / ?EARTH_RADIUS) / ?RAD_FACTOR) of
_GoodResult -> ok
catch
error:Error -> Error;
_:Other -> Other
end.
这是运行 10 次测试的样子:
5> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}
6> my:test(10).
X=169.43178167665917, Y=994.0890019584891
X=106.80009354948483, Y=5318.014760525637
X=483.5152966069006, Y=849.1797017589287
X=413.42192963089917, Y=1813.3077771861872
X=695.5858531252752, Y=6659.873970151745
X=476.4974288029442, Y=3429.9745843747255
X=352.2598626576124, Y=5441.283558914134
X=189.92661305858994, Y=7267.19292963693
X=525.3094754648756, Y=6112.466577043024
X=629.8521203556536, Y=8758.910589712157
ok
在最后一行返回 ok 的事实意味着 add_distance_lat() 执行没有错误。如果有错误,那么你会在这里得到一个 badmatch:
ok = add_distance_lat(X, Y),
因为add_distance_lat() 不会返回ok。这是一个例子:
test() ->
ok = add_distance_lat(12.34567, '10.1111').
add_distance_lat(Lat, Distance) ->
try Lat + ((Distance / ?EARTH_RADIUS) / ?RAD_FACTOR) of
_GoodResult -> ok
catch
error:Error -> Error;
_:Other -> Other
end.
In the shell:
11> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}
12> my:test().
** exception error: no match of right hand side value badarith
in function my:test/0 (my.erl, line 15)
错误表明这一行的右手边:
ok = add_distance_lat(12.34567, '10.1111').
是原子badarith,与原子ok不匹配。
您可以注释掉第一个 test() 示例中的 io:format() 语句,然后运行测试 100,000,000 次。如果返回ok,则没有badarith错误:
7> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}
8> my:test(100000000).
ok
我非常有信心 add_distance_lat() 可以沉着地处理浮点数。
另一方面:
3> my:add_distance_lat(30.45, "20.11").
badarith
4> my:add_distance_lat('1000.24', 12.123412341324).
badarith
正如legoscia 建议的那样,如果您将is_number() 保护添加到您的函数中,那么如果您不提供浮点数或整数作为参数:
add_distance_lat(Lat, Distance) when is_number(Lat), is_number(Distance) ->
Lat + ((Distance / ?EARTH_RADIUS) / ?RAD_FACTOR).
在外壳中:
5> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}
6> my:add_distance_lat(30.45, "20.11").
** exception error: no function clause matching my:add_distance_lat(30.45,"20.11") (my.erl, line 27)
7> my:add_distance_lat('1000.24', 12.123412341324).
** exception error: no function clause matching my:add_distance_lat('1000.24',12.123412341324) (my.erl, line 27)
如果您的数据没有出现function_clause 错误,请查看ct_expand:term 以解决问题。