Erlang records both type restrictions and values, as well as default values

I am trying to write a record that is a bank account:

-record(account, {  name :: atom(),
                    type :: atom(),
                    balance = 0 :: integer()  }).

I also want to limit the balance always >= 0. How to do it?

+5
source share
2 answers

Something like this balance = 0 :: 0 | pos_integer()might do the trick.

edit was not sure if it exists, but non_neg_integer()would be better:

balance = 0 :: non_neg_integer()
+6
source

, , PropEr Dialyzer. balance >= 0, , , :

-module(account).

-record(account, { name :: atom(),
                   type :: atom(),
                   balance = 0 :: non_neg_integer() }).

%% Declares a type whose structure should not be visible externally.
-opaque account() :: #account{}.
%% Exports the type, making it available to other modules as 'account:account()'.
-export_type([account/0]).

%% Account constructor. Used by other modules to create accounts.
-spec new(atom(), atom(), non_neg_integer()) -> account().
new(Name, Type, InitialBalance) ->
    A = #account{name=Name, type=Type},
    set_balance(A, InitialBalance).

%% Safe setter - checks the balance invariant
-spec set_balance(account(), non_neg_integer()) -> account().
set_balance(Account, Balance) when is_integer(Balance) andalso Balance >= 0 ->
    Account#account{balance=Balance};
set_balance(_, _) -> error(badarg). % Bad balance

, - , Java ++. "" , .

balance. , "" ( ).

+6
source

All Articles