【问题标题】:Why 'no function clause matching' even though four parameters are passed to a function of arity of 4?即使将四个参数传递给 4 的元数的函数,为什么“没有函数子句匹配”?
【发布时间】:2026-02-15 02:35:01
【问题描述】:

这是我的代码:

-module(test).
-export([seed_matrix2/0, take_row_and_column/4]).


seed_matrix2() ->
    [0, 0, 1, 0,
     4, 0, 0, 0,
     0, 0, 0, 2,
     0, 4, 0, 0].

take_row_and_column(R, C, AnsMatrix, SideLen) ->
    RowVector = [ V || X <- lists:seq(0, SideLen-1), V <- lists:nth(R*SideLen+X, AnsMatrix) ],
    ColVector = [ V || X <- lists:seq(0, SideLen-1), V <- lists:nth(X*SideLen+C, AnsMatrix) ],
    {RowVector, ColVector}.

这是我调用函数test:take_row_and_column的错误信息:

74> test:take_row_and_column(1, 2, test:seed_matrix2(), 4).
** exception error: no function clause matching 
                    test:'-take_row_and_column/4-lc$^1/1-1-'(0) (/private/tmp/test.erl, line 12)
     in function  test:take_row_and_column/4 (/private/tmp/test.erl, line 12)

当我传递错误数量的参数或未能满足类型保护时,我通常会得到这个。我不明白为什么这段代码会触发no function clause matching

这是erl的版本banner:

Erlang R16B03 (erts-5.10.4) [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

Eshell V5.10.4  (abort with ^G)

【问题讨论】:

    标签: erlang


    【解决方案1】:

    有问题的失败函数是编译器为列表推导生成的函数(注意名称中的“-lc$...”)。看起来这是因为您的生成器 V

    【讨论】:

    • 感谢您的回答。虽然建议的解决方案不能解决问题,但您的回答有助于我理解错误消息!
    【解决方案2】:

    这里是修复:

    take_row_and_column(R, C, AnsMatrix, SideLen) ->
        RowVector = [ lists:nth((R-1)*SideLen+X, AnsMatrix) || X <- lists:seq(1, SideLen-1) ],
        ColVector = [ lists:nth((X-1)*SideLen+C, AnsMatrix) || X <- lists:seq(1, SideLen-1) ],
        {RowVector, ColVector}.  
    

    有问题的代码有两个问题:

    1) lists:seq(0, ...) 应改为 lists:seq(1, ...)lists:nth() 不喜欢零值

    2) erlang 不喜欢 V&lt;-... 部分。需要将整个lists:nth() 调用移动到|| 的左侧

    【讨论】:

    • 如果你的种子矩阵是一个列表的列表,这是更明显的表示,代码会简单得多。
    最近更新 更多