Erlang:右手边值不匹配

标签 erlang pattern-matching

Erlang 程序中的一个常见错误消息如下:

** exception error: no match of right hand side value 'foo'
     in function module:function/2 (file.erl, line 42)

我该如何调试呢?

最佳答案

以下是如何调试此类错误:

  • 转至 module:function/2 (file.erl, line 42)
  • 找到肯定存在的有问题的匹配操作
  • 将左侧替换为 新鲜多变的。在这里,您可能会发现您正在尝试对已绑定(bind)的变量进行模式匹配...
  • 添加电话至 erlang:display/1 使用新变量
  • 再次运行程序以打印该变量的值并了解它为什么与给定模式不匹配

  • 这里有些例子:
  • Example 1 :
    {_, Input} = io:get_line("Do you want to chat?") % Line 42
    

    将此替换为:
    Fresh1 = io:get_line("Do you want to chat?"),
    erlang:display(Fresh1),
    {_, Input} = Fresh1
    

    再次运行程序:
    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)
    

    你可以看到io:get_line/1返回一个字符串而不是一个元组,所以匹配 {_, Input}失败。
  • Example 2 :

    在 Erlang shell 中:
    2> Pid = echo:start().
    ** exception error: no match of right hand side value <0.41.0>
    

    这里的变量 Pid 肯定是 已绑定(bind)到另一个值...
    3> Pid.
    <0.39.0>
    

    您可以使用 f(Var) 让 shell 忘记这样的绑定(bind)。或 f() :
    4> f(Pid).
    ok
    5> Pid.
    * 1: variable 'Pid' is unbound
    6> Pid = echo:start().
    <0.49.0>
    
  • 关于Erlang:右手边值不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23577935/

    相关文章:

    Erlang 模式与别名匹配

    dictionary - Erlang异常错误-没有函数子句匹配列表:map - what am I missing?

    java - 正则表达式从字符串中提取以逗号分隔的字符串

    c# - 模式匹配案例 when

    Mastermind 游戏的字符串比较

    erlang - 如何自动删除动态主管中已终止子项的规范

    erlang - ejabberd的IP地址

    erlang - 如何检查输入是否是Erlang中的字符串?

    Java 模式匹配器错误匹配的子字符串

    algorithm - 在图像算法上计数对象