[erlang-questions] record updating with several functions

Alain O'Dea <>
Sun Jan 23 22:54:56 CET 2011


On 2011-01-23, at 8:35, "info" <> wrote:

> Hi Alain,
>  
> According to your explanation, I modified my example:
>  
> -record (field,{ch1,ch2}).
> testrecord()->
> Record = functionA(#field{}),
>     io:format("M: ch1 is ~s ch2 is ~s~n",[Record#field.ch1,Record#field.ch2]).
> functionA(RecA)-> 
> R1=RecA#field{ch1 = "hello"},
> io:format("FA: ch1 is ~s ch2 is ~s~n",[R1#field.ch1,R1#field.ch2]),   
> RecB = functionB(R1),
> RecB.
> functionB(RecB)-> 
> R2=RecB#field{ch2 = "boy"},
> io:format("FB: ch1 is ~s ch2 is ~s~n",[R2#field.ch1,R2#field.ch2]),
> R2.
>  
> Now it's ok but I find the solution "hard" (I don't find the good term in english ...). I suppose that a good erlang programmer will not solve the problem like this ?
> Regards, 
>  
> J-Ph. Constantin
> ITS3 Genève
> www.its3.ch

Hi:

The english term you are looking for is "awkward" ;)

It certainly is awkward, but not far from what you'd do in production Erlang code.

Normally, an experienced Erlang/OTP programmer would use OTP generic behaviours and callback modules.  This is a pretty advanced topic, but there is a very good book by Eric Merritt, Martin Logan and Richard Carlsson called Erlang and OTP in Action http://manning.com/logan.

When you use an OTP behaviour callback module each callback function is handed a request, a sender PID and the State.  The State is like this fields record you are working with.  It is an opaque data structure that your callback module owns the internal details of.  Each of your callback functions returns a reply with a new version of the State (or just the old state if nothing needs to change).

If you want to get serious about code structure in Erlang, then OTP is the idiomatic approach.

However, I seriously suggest that you become comfortable with the syntax and the semantics of sequential Erlang before getting into OTP.  Learn You Some Erlang at http://learnyousomeerlang.com/ is a great tutorial supported by Erlang Solutions.  It has a sense of humour and it presents the topics in an easy to follow format.  It flows well and it will really answer most of your questions about the language.

Please work through Learn You Some Erlang and post any questions or problems you have back to erlang-questions so that one of the other members of the community or I can assist you :)

When replying to Erlang-questions remember to Reply All if you want it on the mailing list.  Also leave the message body intact and add your reply inline or below the body of the email you are replying to.  This makes it easier to follow the thread ;)

Best regards,
Alain


More information about the erlang-questions mailing list