Matching elements of records

Bjorn Gustavsson <>
Wed Oct 27 12:40:45 CEST 2004


The compiler will generate slightly more efficient code for
test1/1.

Also, I find test1/1 much easier to read. It is the style I
use all the time (except that I place the Foo variable to
right of the #foo{} pattern, but that is just a matter of
personal preference).

/Bjorn

Fredrik Thulin <> writes:

> Hi
> 
> In my application, I find that I often pass records to functions and 
> want to end up in different instances of the functions depending on 
> some element of the record.
> 
> I have done this like test2() below does in a number of places, but I 
> would want to to reduce length of fun() lines and to avoid problems in 
> the emacs-mode indentation (*) with '#' after 'when'.
> 
> Considering the following example code (as far as I can tell, both test1
> () and test2() accomplishes what I want), is any of them crazy or in 
> some way worse than the other?
> 
> 
> -module(t).
> -compile(export_all).
> 
> -record(foo, {one, two}).
> 
> 
> test1(Foo=#foo{one=1}) ->
>     io:format("in test1 #1: ~p~n", [Foo]),
>     is_one;
> test1(Foo=#foo{one=2}) ->
>     io:format("in test1 #2: ~p~n", [Foo]),
>     is_two.
> 
> test2(Foo) when is_record(Foo, foo), Foo#foo.one == 1 ->
>     io:format("in test2 #1: ~p~n", [Foo]),
>     is_one;
> test2(Foo) when is_record(Foo, foo), Foo#foo.one == 2 ->
>     io:format("in test2 #2: ~p~n", [Foo]),
>     is_two.
> 
> do() ->
>     R=#foo{one=2, two=bar},
>     io:format("test1 result : ~p~n", [test1(R)]),
>     io:format("test2 result : ~p~n", [test2(R)]),
>     ok.
> 
> 
> Result :
> 
> 14> t:do().
> in test1 #2: {foo,2,bar}
> test1 result : is_two
> in test2 #2: {foo,2,bar}
> test2 result : is_two
> ok
> 15>
> 
> /Fredrik
> 
> *) Emacs mode (the one distributed with R10B-0) does not align the 
> "Foo#foo.one == 1" with the "is_record(Foo, foo)" if you want to break 
> the line :
> 
> test2(Foo) when is_record(Foo, foo), 
> Foo#foo.one == 1 ->
> 
> rather than 
> 
> test2(Foo) when is_record(Foo, foo), 
>                 Foo#foo.one == 1 ->
> 
> It works with non-record variables, like :
> 
> test2(Foo, Bar) when is_record(Foo, foo), 
>                      Bar == 1 ->
> 

-- 
Björn Gustavsson, Erlang/OTP, Ericsson AB



More information about the erlang-questions mailing list