When pattern matching maps in Erlang, why is this variable unbound?

前端 未结 3 1993
情书的邮戳
情书的邮戳 2021-01-13 04:16
-module(count).
-export([count/1]).

count(L) when is_list(L) ->
  do_count(L, #{});
count(_) ->
  error(badarg).

do_count([], Acc) -> Acc;
do_count([H|T],         


        
3条回答
  •  北海茫月
    2021-01-13 04:27

    I made up this rule for myself: when using maps in the head of a function clause, the order of matching is not guaranteed. As a result, in your example you can't count on a [H|T] match to provide a value for H.

    Several features of maps look like they should work, and Joe Armstrong says they should work, but they don't. It's a dumb part of erlang. Witness my incredulity here: https://bugs.erlang.org/browse/ERL-88

    Simpler examples:

    do_stuff(X, [X|Y]) ->
        io:format("~w~n", [Y]).
    
    test() ->
        do_stuff(a, [a,b,c]).
    
    4> c(x).
    {ok,x}
    
    5> x:test().
    [b,c]
    ok
    

    But:

    -module(x).
    -compile(export_all).
    
    do_stuff(X, #{X := Y}) ->
        io:format("~w~n", [Y]).
    
    test() ->
        do_stuff(a, #{a => 3}).
    
    
    8> c(x).
    x.erl:4: variable 'X' is unbound
    

提交回复
热议问题