[erlang-questions] When to return {ok, Value} or just the Value

Michael Uvarov <>
Sun Nov 13 08:57:57 CET 2011


Hi

It is better to return Value, because you can use this value in HOFs:
fun2(fun1()).
And if an error was occurred, just skip it.
For example,

avg(L) when is_list(L) -> lists:sum(L) / erlang:length(L).

This function will fail for []. Let it crash.

For {ok, Value} you should check always the returned value:
{ok, Value} = re:compile("test").


BIFs and NIFs return {ok, Value} or {error, Reason}, because it is only one
way to return the reason of the error from C-code. There is no the throw()
construction for NIFs. There is only error:badarg, which is not always
helpful. For example, the function ets:lookup_element/3 can throw
error:badarg when first argument is not a table id or if there is no an
entry.


-- 
Best regards,
Uvarov Michael
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20111113/c9cbd2ff/attachment.html>


More information about the erlang-questions mailing list