[erlang-questions] How to math list of record

Raimo Niskanen raimo+erlang-questions@REDACTED
Tue Dec 13 10:42:09 CET 2016


On Tue, Dec 13, 2016 at 09:20:10AM +0000, Sergey Safarov wrote:
> I want check type of passed arguments. In following example i can check
> record type

The term "check type" is misleading.  In Erlang you select a code path
depending on the type i.e checking when doing something with it.  So if you
have a function that does nothing but crash for the wrong type that might
be regarded as a type checking function, but in Erlang you in general do
not check the type until you do something with the term.

Unless you want to check the type in an API to report errors as early as
possible...

> 
> -record(person, {first_name, last_name}).
> my_func(#person{} = Arg) -> Arg.
> 
> It works.
> But how to do check of list of records? Like this
> 
> -record(person, {first_name, last_name}).
> my_func([#person{} | ... ] = Arg) -> Arg.

You will have to traverse the list to check all elements of the list.  This
is O(1) so in general you do not check a whole list just for fun.  Instead
you let it crash on invalid types while processing.

Since processing a list is O(1) you loose just a constant factor by
processing the list twice, so you could add a type checking pass over the
list, but that is mostly just adding complexity...  Just checking a record
type still does not check the record fields nor contradictions between
fields or any other problems with the records.

my_func_check([#person{} | Persons]) ->
    my_func_check(Persons);
my_func_check([]) ->
    ok.

my_func(Arg) ->
    my_func_check(Arg),
    ...

> 
> Thanks


-- 

/ Raimo Niskanen, Erlang/OTP, Ericsson AB



More information about the erlang-questions mailing list