[erlang-questions] Finding records in List

Kostis Sagonas <>
Thu Jan 13 22:48:40 CET 2011


David Mercer wrote:
> On Thursday, January 13, 2011, Bengt Kleberg wrote:
> 
>> is_name_and_age( Person, Name, Age ) ->
>> 	(Person#person.name =:= Name) andalso (Person#person.age =:= Age)
> 
> Question about style: is there any preference between what Bengt wrote, and:
> 
> 	is_name_and_age(#person{name = Name, age = Age}, Name, Age) -> true;
> 	is_name_and_age(_,_,_) -> false.
> 
> In fact, I think I like Bengt's better, since it is more clear about intent,
> but I'd have written it as the latter figuring that that was more idiomatic.

Bengt's version, although more type-correct than yours, IMO is verbose 
without any particular reason. If you want a more compact version with 
only one clause, which is another advantage I see in Bengt's version, 
write the following:

    is_name_and_age(#person{name = N, age = A}, Name, Age) ->
	N =:= Name andalso A =:= Age.

with or without parentheses around the andalso arguments.

This version makes it crystal clear that the first argument has to be a 
#person{} record (and does not return 'false' by accident if called with 
something else in its first argument). It also has the advantage that 
the clause head can be read without having to pay special attention to 
the non-linearity of the clause head variables.

Kostis


More information about the erlang-questions mailing list