[erlang-questions] Update with complicated data structure

Rich Neswold rich.neswold@REDACTED
Mon Nov 23 17:37:46 CET 2015


On Mon, Nov 23, 2015 at 4:06 AM, YuanZhiqian <on-your-mark@REDACTED>
wrote:

>
> -record(company_info, {
>         company_id,
>         budget,
>         consumption,
>         compaign_ids
>     }).
>
> cal_win_notice({Co_id, Ca, Adgrp, Price, Cur},
>     #state{company_list = Co_list, campaign_list= Ca_list} = State) ->
>     case lists:any(fun(#company_info{company_id = A}) -> A == Co_id end,
>             Co_list) of
>         true ->
> *            New_co_list = lists:map(fun(R) -> *
> *                        case R#company_info.company_id of*
> *                            Co_id ->*
> *                                R#company_info{consumption =
> R#company_info.consumption + Price};*
> *                            _ ->*
> *                                R*
> *                        end*
> *                    end,*
> *                Co_list),*
> *            {ok, State#state{company_list = New_co_list}};*
>         false ->
>             {not_found, State}
>     end.
>

Something like this (not compiled or tested):

cal_win_notice({Co_id, _, _, Price, _}, #state{company_list=Co_list}=State)
->
    case lists:mapfoldl(fun (#company_info{company_id=CID, consumption=C} =
E, _)
                          when CID == Co_id ->
                                {E#company_info{consumption=C + price},
true};
                            (E, Acc) ->
                                {E, Acc}
                        end, false, Co_list) of
     {_, false} -> {not_found, State};
     {NL, true} -> {ok, State#state{company_list=NL}}
    end.

This only makes a single pass through the list. If you need to update more
than one field, you do it in the same update. For instance, if you need to
add $1000 to the budget, as well (ignoring whether it makes sense in this
function) replace line 4 with:

                                {E#company_info{consumption=C + price,
                                                budget=B + 1000}, true};

(you'll also have to pattern-match B with the budget field in line 2.)

-- 
Rich
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20151123/6447eda5/attachment.htm>


More information about the erlang-questions mailing list