<div dir="ltr"><br><div><br><div class="gmail_quote"><div dir="ltr">On Tue, Dec 6, 2016 at 5:52 AM qp <<a href="mailto:quantumpotato@gmail.com">quantumpotato@gmail.com</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div dir="ltr" class="gmail_msg"><div class="gmail_msg"><div class="gmail_msg">Hi, I am new to Erlang and wrote this code for validating that the Name, Action & Target atoms passed in to validRequest are all valid.<br class="gmail_msg"><br class="gmail_msg"></div></div></div></blockquote><div><br>Another solution is this:<br><br>Let us start by assuming the presence of functions of this form:<br><br>-spec valid_name(Target) -> {name, Name} | {error, Reason}.<br>-spec valid_action(Target) -> {action, Name} | {error, Reason}.<br>-spec valid_request(Target) -> {request, Name} | {error, Reason}.<br><br>We would like to set up a verifier which either returns a context, or fails with the errors present in that context:<br><br></div><div>-type context() :: #{ name := any(), action := any(), request := any(), _ => _ }.<br><br></div><div>-spec verify(Target) -> {ok, context()} | {error, [Reason]}.<br><br>The context contains input-coerced, verified data and is represented as a map in order to make it easier to users to process that context later on.<br><br>verify(Target) -><br>    ErrorF = fun<br>                ({error, _}) -> true;<br>                (_) -> false<br>            end,<br>    case lists:partition(ErrorF, [valid_name(Target),<br>                                  valid_action(Target),<br>                                  valid_request(Target)]) of<br>        {OK, []} -><br>            {ok, maps:from_list(OK)};<br>        {_, Errs} -><br>            {error, Errs}<br>    end.<br><br></div><div>The function uses 'lists:partition/2' to split the errors away from the valid outputs. Then we can simply match on the errors: if there are none, we proceed with the context. If there are errors, return them all.<br><br></div></div></div></div>