<html>
<head>
<style><!--
.hmmessage P
{
margin:0px;
padding:0px
}
body.hmmessage
{
font-size: 12pt;
font-family:΢ÈíÑźÚ
}
--></style></head>
<body class='hmmessage'><div dir='ltr'>Hi Richard,<div><br></div><div>  Thanks for your elaborative comments. Some of the advices are helpful and I appreciate a lot for that; but some of them are not quite on the track ...</div><div><br></div><div>  For example, regarding the array size issue, you see, it's just a sample where my point is focused on the assignment expression, so I use an array instead of a hash table which I actually have used in my project, for that would make the code messed up with less important parts. I am certainly not a C language tard = =</div><div><br></div><div>  And please allow me to clarify my purpose of this question, this is not an erlang v.s. c&c++ debate, I am just facing an actual problem in real scenario, and need some practical advice.</div><div><br></div><div>  So it is not that I insist in making erlang behave the same as imperial language, but that it is a real requirement in the project that I'm trying to solve.</div><div><br></div><div>  As for the naming issue ... ok you are right, but does it really matter? At least not as important in my case ...</div><div><br></div><div>  And you are asking me why I am using size_t instead of int, I don't know if I am right, but size_t seems an intended type for array indices, since it is unassigned, and codes from google use size_t as well. Try to compile using int, but configure your error level to the most strict mode, turn on "warning as error" option, then you won't get the code compiled.</div><div><br></div><div>  So the point is, thanks again for your help, but unfortunately I am getting more confused with too much irrelevant comments.</div><div><br></div><div>Best regards</div><div>Zhiqian</div><div><br><div>> Subject: Re: [erlang-questions] Update with complicated data structure<br>> From: ok@cs.otago.ac.nz<br>> Date: Tue, 24 Nov 2015 17:34:05 +1300<br>> CC: erlang-questions@erlang.org<br>> To: on-your-mark@hotmail.com<br>> <br>> <br>> On 23/11/2015, at 11:06 pm, YuanZhiqian <on-your-mark@hotmail.com> wrote:<br>> <br>> > Hi Guys,<br>> > <br>> >   Sorry to bother you again... I am totally a green hand in Erlang :(<br>> > <br>> >   Here is the problem I am now struggling with: in C&C++, we are always able to update a field in an object simply using obj.field1 = Value; But in Erlang, since its once-bound-never-change policy, people would have to find a way around to achieve the same goal,<br>> <br>> Be VERY VERY CLEAR what "THE SAME GOAL" really means.<br>> <br>> It does *not* mean "fighting the language on the beaches,<br>> on the landing grounds, in the fields and the streets,<br>> (and) in the streets" and "never surrender"ing in your<br>> determination to *FORCE* the low level imperative style<br>> on your functional language.<br>> <br>> It means achieving the same APPLICATION-LEVEL GOAL (not<br>> code-level goal) by some possibly very different means.<br>> <br>> > and things are getting worse when the data structure is a little more complicated, which is my case:<br>> > <br>> >   I have a list of records, whose definition is as follows<br>> > <br>> > -record(company_info, {<br>> >         company_id,<br>> >         budget,<br>> >         consumption,<br>> >         compaign_ids<br>> >     }).<br>> > <br>> > What I want to do is to add a value to the consumption of the record whose company_id is given, and returning error message if there's no such record found.<br>> <br>> We stop right there.<br>> First, you are presuming a structure in which you don't<br>> KNOW whether a company-id is present or not.<br>> Why?<br>> Second, you are using a list, which is a very nice data<br>> structure, but the catalogue of things lists are good at<br>> does not include "searching".  You might find gb_trees:<br>> more apt to your needs.<br>> <br>>     case gb_trees:lookup(Company_Id, Companies)<br>>       of none -> raise whatever exception you want<br>>        ; {value,Company_Info=#company_info{budget=Old}} -><br>>          Updated =<br>>             Company_Info#company_info{budget = Old + Delta},<br>>          gb_trees:update(Company_Id, Updated, Companies)<br>>     end<br>> <br>> You should probably break this into two small functions:<br>> <br>> % (K, gbtree(K,V), (V -> V)) -> gbtree(K,V).<br>> <br>> update(Key, Tree, Fun) -><br>>     gb_trees:update(Key, Fun(gb_trees:get(Key, Tree)), Tree).<br>> <br>> increment_consumption(Info, Delta) -><br>>     Info#company_info(Info#company_info.consumption + Delta).<br>>          <br>> ... update(Company_Id, Companies, fun (Info) -><br>>         increment_consumption(Info, Delta) end)<br>> ...<br>> <br>> <br>> > Written in C, that would be:<br>> > <br>> > ///////////////////////////////////In C&C++///////////<br>> > CompanyInfo co_list[1000];<br>> > /* initialized somewhere else ... */<br>> > <br>> > for (size_t i = 0; i < 1000; ++i) {<br>> >   if (co_list[i].comany_id == co_id) {<br>> >     co_list[i].consumption += price;  <br>> >     break;<br>> >   }<br>> > }<br>> > <br>> > if (i == 1000)<br>> >   err_msg = "bla...";<br>> > //////////////////////////////////////////////////////<br>> <br>> Written in C that would be DISASTROUS if you ever had<br>> 1001 companies...  (Where did this practice of using<br>> size_t for indices come from?  That's what 'int' is for!)<br>> <br>> (a) You need to break your Erlang code into smaller,<br>>     individually meaningful pieces.<br>> <br>> (b) You need to consider AND DOCUMENT why you want to<br>>     use a data structure that takes linear time and<br>>     turns over linear space for an update, when a data<br>>     structure offering logarithmic time and space turnover<br>>     is available.<br>> <br>> (c) List comprehensions are generally easier to read than<br>>     calls to lists:map/2.<br>> <br>> (d) Avoid thinking in terms of Booleans;<br>>     also, use pattern matching more.<br>>     case [Info || Info = #company_info{company_id = Co_Id} <- Companies]<br>>       of [Found] -> ...<br>>        ; [] -> no match<br>>        ; [_,_|_] -> multiple matches<br>>     end<br>>     Thinking in terms of lists:any made it impossible for you<br>>     to notice duplicate entries; writing<br>>     [Found] = [C || C = #company_info{company_id = Co_Id} <- Companies]<br>>     makes it impossible NOT to notice.<br>> <br>> (e) Since the record is a 'company_info' record, what is the<br>>     point of calling the key field 'company_id' rather than<br>>     just 'id'?  You didn't call 'budget' 'company_budget'.<br>> <br>> <br>> <br>> > <br>> > But in Erlang, I couldn't find a straightforward way to do this, my code is like this:<br>> > <br>> > ////////////////////////////In Erlang//////////////////////////<br>> > %Co_list is the list of company_info records<br>> > <br>> > cal_win_notice({Co_id, Ca, Adgrp, Price, Cur}, <br>> >     #state{company_list = Co_list, campaign_list= Ca_list} = State) -><br>> <br>> (f) Hvy abbrvtn mks ths hrd 2 ndrstnd.<br>> (g) Why do you have a mixed tuple that is not a record<br>>     and is not separate arguments?<br>> <br>> >     case lists:any(fun(#company_info{company_id = A}) -> A == Co_id end, <br>> >             Co_list) of<br>> >         true -> <br>> >             New_co_list = lists:map(fun(R) -> <br>> >                         case R#company_info.company_id of<br>> >                             Co_id -><br>> >                                 R#company_info{consumption = R#company_info.consumption + Price};<br>> >                             _ -><br>> >                                 R<br>> >                         end<br>> >                     end,<br>> >                 Co_list),<br>> >             {ok, State#state{company_list = New_co_list}};<br>> >         false -><br>> >             {not_found, State} <br>> >     end.<br>> <br>> No doubt you have a good reason for returning {not_found,State}<br>> instead of crashing (raising an exception), but it's probably<br>> worth documenting it.  I say this because this is hard to<br>> compose: when you call your function you will have to handle<br>> two possible outcomes.  Notice how my code got simpler when<br>> I switched from gb_trees:lookup/2 to gb_trees:get/2.<br>> <br>> > Well, as shown above, the codes in bold fonts are doing the same logic which in C can be done in just one expression.<br>> <br>> It wasn't one expression in C.<br>> It was 6 statements, including at least one capacity bug.<br>> You have to look at the *whole* thing, not just one tiny<br>> bit of it.<br>> <br>> > This will certainly make the code unnecessarily verbose when there are more similar operations to come. What should I do? I think this is due to Erlang's feature, but in case I am wrong and making a simple thing complicated ...<br>> <br>> Yes you are,<br>> by insisting that it be done the way you would do it in C.<br>> <br>> Make the code out of small composable pieces that are<br>> separately meaningful. <br>> <br>> <br></div></div>                                        </div></body>
</html>