How do I elegantly check many conditions in Erlang?

前端 未结 4 1814
清歌不尽
清歌不尽 2020-12-23 15:28

So when a user sends a request to register an account, they send their username, password, email, and other info. The registration function must verify all of their data. An

4条回答
  •  情深已故
    2020-12-23 16:01

    Building up on @JLarky's answer, here's something that i came up with. It also draws some inspiration from Haskell's monads.

    -record(user,
        {name :: binary(), 
         email :: binary(), 
         password :: binary()}
    ).
    -type user() :: #user{}.
    -type bind_res() :: {ok, term()} | {error, term()} | term().
    -type bind_fun() :: fun((term()) -> bind_res()).
    
    
    -spec validate(term(), [bind_fun()]) -> bind_res().
    validate(Init, Functions) ->
        lists:foldl(fun '|>'/2, Init, Functions).
    
    -spec '|>'(bind_fun(), bind_res())-> bind_res().
    '|>'(F, {ok, Result}) -> F(Result);
    '|>'(F, {error, What} = Error) -> Error;
    '|>'(F, Result) -> F(Result).
    
    -spec validate_email(user()) -> {ok, user()} | {error, term()}. 
    validate_email(#user{email = Email}) ->
    ...
    -spec validate_username(user()) -> {ok, user()} | {error, term()}.
    validate_username(#user{name = Name}) ->
    ...
    -spec validate_password(user()) -> {ok, user()} | {error, term()}.    
    validate_password(#user{password = Password}) ->
    ...
    
    validate(#user{...}, [
        fun validate_email/1,
        fun validate_username/1,
        fun validate_password/1
    ]).
    

提交回复
热议问题