[erlang-questions] Update with complicated data structure

YuanZhiqian on-your-mark@REDACTED
Tue Nov 24 09:11:36 CET 2015


Hi Jesper, 
  Thanks a lot! I'll dig into it.
Best regardsZhiqian

From: jesper.louis.andersen@REDACTED
Date: Mon, 23 Nov 2015 22:22:55 +0100
Subject: Re: [erlang-questions] Update with complicated data structure
To: on-your-mark@REDACTED
CC: erlang-questions@REDACTED


On Mon, Nov 23, 2015 at 11:06 AM, YuanZhiqian <on-your-mark@REDACTED> wrote:
Sorry to bother you again... I am totally a green hand in Erlang :(
Suppose for the moment you are willing to use a map to store all your records. Then we can simplify the code quite a lot. List-representations are best used if you often process all of the the elements in the list, or you can use any element of the list, particularly the first one. If you are pin-pointing a specific entry, the map is a far better data structure. First a module definition:
-module(z).-export([cal_win_notice/2]).
Next, lets hack up a couple of records to match what is going on in your code:
-record(state, {        '...',        companies,        campaigns}).
-record(company_info, {        id,        budget,        consumption,        campaigns}).
The mapply/3 function here tries to apply F to the map value given by the key ID. If no such ID exists, it leaves the map alone.
mapply(F, ID, Map) ->    case maps:get(ID, Map, undefined) of        undefined -> Map;        T -> Map#{ ID := F(T) }    end.
Now, we can use this function. Make an F which does what we want. Then apply it. We can check if any change were made to the map by matching on the unchanged map. Otherwise, the map has been changed, and we can update the map with the new one.
cal_win_notice({CoID, _Ca, _AdGrp, Price, _Cur}, #state { companies = Cos } = State) ->    F = fun(#company_info{ consumption = Cons } = X) -> X#company_info{ consumption = Cons + Price } end,    case mapply(F, CoID, Cos) of        Cos -> {not_found, State}; %% Unchanged map        Changed -> {ok, State#state { companies = Changed }}    end.
Want to make two changes?
G = fun(#company_info { consumption = Cons } = X) -> X#company_info { consumption = Cons - Price } end,
compose(F, G) ->    fun(X) -> G(F(X)) end.
then mapply(compose(F, G), CoID, Cos) ...


-- 
J.
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20151124/bd4f1921/attachment.htm>


More information about the erlang-questions mailing list