How to specify(force) the Data Type of fields in records.
Hugo Mills
hugo@REDACTED
Tue Jul 7 22:02:07 CEST 2020
On Tue, Jul 07, 2020 at 10:21:42PM +0300, Papa Tana wrote:
> Hi All,
>
> I would like to create a Record, with Strict Data Type as Input:
> - name must be a string
> - price must be an atom
> - address must be an Ip address
> - rest can be anything
>
> Here is my code:
>
> -module(mym).
>
> -type personal_name() :: string().
> -type personal_price() :: atom().
> -type personal_address() :: inet:ip_address().
>
> -record(computer, {
> name :: personal_name(),
> price :: personal_price(),
> address :: personal_address(),
> rest }).
>
> -export([start/0]).
>
> start()->
> C = #computer{
> name= blaster,
> price= "55.0",
> address= <<0:8>> },
>
> {is_record(C, computer),C}.
>
> When I run it:
>
> 1> mym:start().
> {true,{computer,blaster,"55.0",<<0>>,undefined}}
> 2>
>
> undefined is normal, but:
> * name= blaster, %% I put an atom, I want it to be accepted only if a string
> * price= "55.0", %% should accept only atom
> * address= <<0:8>>, %% shoul accept only ip_address, not binary
>
> Could you please tell me how to specify(force) the Data Type of these
> input value?
>
> Thanks,
The type annotations you're using here aren't actually looked at or
checked by the compiler. Instead, there's a separate tool called
"dialyzer", which can be used to verify expected types of functions,
and whether those functions might be successful.
If you're dealing with external input, validate that input (by, for
example, guard expressions such as the is_* functions from the erlang
module) as soon as possible. If you do that, dialyzer can determine
that subsequent uses of those variables are particular types, and can
do a good job of verifying that the rest of your code is type-safe.
Hugo.
--
Hugo Mills | Be pure.
hugo@REDACTED carfax.org.uk | Be vigilant.
http://carfax.org.uk/ | Behave.
PGP: E2AB1DE4 | Torquemada, Nemesis
More information about the erlang-questions
mailing list