Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between function_clause and badarg in Erlang?

Sometimes I get badarg instead of function_clause but I cannot see the rule that would determine which one is going to appear.

As I understand, function_clause is thrown when no function's implementation matches given arguments. About badarg the documentation says

The argument is of wrong data type, or is otherwise badly formed.

which seems to be covered by function_clause conditions...

For instance

lists:flatten(3).

throws clause error, while the type definitely does not match.

like image 615
radrow Avatar asked Dec 20 '25 03:12

radrow


1 Answers

Function clauses are parts of definition with different argument patterns/guards, as in

func({X, Y}) -> ...;
func(X) when X > 10 -> ...;
func(_) -> ...

function_clause means that none of them matched. There are similar if_clause and case_clause. For flatten with single argument there is only one clause

flatten(List) when is_list(List) ->
    do_flatten(List, []).

which doesn't match 3, which is why you get function_clause.

So

Sometimes I get badarg instead of function_clause but I cannot see the rule that would determine which one is going to appear

This is basically an implementation detail which you should only care about when debugging the implementation of that function.

like image 99
Alexey Romanov Avatar answered Dec 22 '25 00:12

Alexey Romanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!