Vombat
Vombat

Reputation: 1166

Erlang record handling using filter

I have the following code to return a record from a list of records that has a field with value equal to Accountnumber.

lookup(AccountNumber, [#account{no=AccountNumber} = Rec | _]) ->
    Rec;
lookup(AccountNumber, [_| T]) ->
    lookup(AccountNumber, T);
lookup(AccountNumber, []) ->
    not_found.

The above code works fine, but when I try to convert it to filter using the following code:

lookup(AccountNumber, DBRef) ->
    lists:filter(fun(#account{no=AccountNumber} = Rec) -> Rec end, DBRef).

I got the following error:

** exception error: no case clause matching #account{no = 2,balance = 0,pin = undefined,name = "Ali",
                                                 transactions = []}
   in function  lists:'-filter/2-lc$^0/1-0-'/2 (lists.erl, line 1271)

What is the reason for the error?

Upvotes: 0

Views: 556

Answers (1)

Vinod
Vinod

Reputation: 2243

There are multiple problems in the code

1.The filter should always return atom true or false for all list elements. This is causing you the error.

2.When the variable outside the fun block is used in fun header, they are not patterned matched, the variable outside is masked. Hence the pattern match fails.

You can see the modified code below.

  lookup(AccountNumber, DBRef)  ->
    lists:filter(
      fun(#account{no=AccNo}) when AccNo =:= AccountNumber -> true;
         (_) -> false 
      end, DBRef).

Upvotes: 6

Related Questions