[erlang-questions] The way of accessing record's attributes.

Raimo Niskanen raimo+erlang-questions@REDACTED
Tue Nov 8 16:35:43 CET 2016


On Tue, Nov 08, 2016 at 04:21:59PM +0100, Alex Feng wrote:
> Thank you all for the detailed explanation, I guess I was trying to use
>  "C/C++" way of thinking to understand <record>.

This corresponds to the case in C where you have a void *, then you have to
cast it to the appropriate (struct robot *) before accessing a field
->hobbies in it.

In Erlang you can not declare the type of a variable, which seems to be the
C/C++ thinking you fell into.  Type is a run-time property in Erlang.

(except when using the static type checker Dialyzer)


> 
> Br,
> Alex
> 
> 2016-11-08 15:41 GMT+01:00 Raimo Niskanen <
> raimo+erlang-questions@REDACTED>:
> 
> > On Tue, Nov 08, 2016 at 02:12:35PM +0100, Alex Feng wrote:
> > > Hi,
> > >
> > > Does anyone know why erlang has to attach the record's name to be able to
> > > access an attribute ?
> > > I don't understand, for example, the record "#robot" has been assigned to
> > > variable "Crusher", why do we have to use  "Crusher#robot.hobbies"
> > instead
> > > of "Crusher.hobbies" ?
> >
> > Records is a compile time syntactical sugar on tagged tuples.
> >
> > So "Crusher#robot.hobbies" is translated to something like
> >   begin robot = element(1, Crusher), element(3, Crusher) end
> > if 'hobbies' is the second element of #robot.
> >
> > The compiler can not know that it is the hobbies field from the #robot
> > record you want to extract unless told so.  You may mean the hobbies field
> > from the #whatever record.  It could see that it is a #robot record from an
> > earlier assignment in the same code and warn about it if it's not,
> > but in the general case it can not know what is stored in the variable
> > hence leaves it to be solved in runtime.
> >
> >
> > >
> > >
> > > 5> Crusher = #robot{name="Crusher", hobbies=["Crushing people","petting
> > > cats"]}.
> > > #robot{name = "Crusher",type = industrial,
> > > hobbies = ["Crushing people","petting cats"],
> > > details = []}
> > > 6> Crusher#robot.hobbies.
> > > ["Crushing people","petting cats"]
> > >
> > >
> > > Br,
> > > Alex
> >
> > > _______________________________________________
> > > erlang-questions mailing list
> > > erlang-questions@REDACTED
> > > http://erlang.org/mailman/listinfo/erlang-questions
> >
> >
> > --
> >
> > / Raimo Niskanen, Erlang/OTP, Ericsson AB
> > _______________________________________________
> > erlang-questions mailing list
> > erlang-questions@REDACTED
> > http://erlang.org/mailman/listinfo/erlang-questions
> >

> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions


-- 

/ Raimo Niskanen, Erlang/OTP, Ericsson AB



More information about the erlang-questions mailing list