aro*_*tav 3 erlang pattern-matching
Erlang程序中的常见错误消息如下:
** exception error: no match of right hand side value 'foo'
in function module:function/2 (file.erl, line 42)
Run Code Online (Sandbox Code Playgroud)
我该怎么调试呢?
以下是调试此类错误的方法:
去 module:function/2 (file.erl, line 42)
找到肯定存在的违规匹配操作
用新变量替换左侧.在这里,您可能会发现您正在尝试与已绑定的变量进行模式匹配...
erlang:display/1使用新变量添加调用
再次运行程序以打印此变量的值,并了解它与给定模式不匹配的原因
这里有些例子:
例1:
{_, Input} = io:get_line("Do you want to chat?") % Line 42
Run Code Online (Sandbox Code Playgroud)
将其替换为:
Fresh1 = io:get_line("Do you want to chat?"),
erlang:display(Fresh1),
{_, Input} = Fresh1
Run Code Online (Sandbox Code Playgroud)
再次运行程序:
1> module:run().
Do you want to chat? Yes
"Yes\n"
** exception error: no match of right hand side value "Yes\n"
in function module:function/2 (file.erl, line 44)
Run Code Online (Sandbox Code Playgroud)
您可以看到io:get_line/1返回字符串而不是元组,因此匹配{_, Input}失败.
例2:
在Erlang shell中:
2> Pid = echo:start().
** exception error: no match of right hand side value <0.41.0>
Run Code Online (Sandbox Code Playgroud)
这里变量Pid肯定已经绑定到另一个值......
3> Pid.
<0.39.0>
Run Code Online (Sandbox Code Playgroud)
您可以使外壳忘记这样一个用结合f(Var)或f():
4> f(Pid).
ok
5> Pid.
* 1: variable 'Pid' is unbound
6> Pid = echo:start().
<0.49.0>
Run Code Online (Sandbox Code Playgroud)