ガード - Erlangの勉強
ガードは、パターン照合に条件を付与することができる。カンマ区切りで論理積になり、セミコロン区切りで論理和となる。
cource(X) when is_integer(X), X > 0 -> "cource No." ++ integer_to_list(X);
cource(X) when is_integer(X), X =:= 0 -> "cource is ALL";
cource(X) -> "cource is bad!".
こうしておけば、
1> restaurant:cource(1).
"cource No.1"
2> restaurant:cource(0).
"cource is ALL"
3> restaurant:cource(aa).
"cource is bad!"
となる。
論理和で上記の関数を定義していると結果は当然、
1> restaurant:cource(1).
"cource No.1"
2> restaurant:cource(0).
"cource No.0"
3> restaurant:cource(aa).
=ERROR REPORT==== 4-Jan-2009::23:03:07 ===
Error in process <0.30.0> with exit value: {badarg,[{erlang,integer_to_list,[aa]},{restaurant,cource,1},{erl_eval,do_apply,5},{shell,exprs,6},{shell,eval_loop,3}]}
** exited: {badarg,[{erlang,integer_to_list,[aa]},
{restaurant,cource,1},
{erl_eval,do_apply,5},
{shell,exprs,6},
{shell,eval_loop,3}]} **
こうなる。最後の、引数がアトムのときの例外は、integer_to_list()の部分で発生している。