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

Hugo Mills hugo@REDACTED
Tue Nov 8 15:39:17 CET 2016


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" ?

   First, note that records are a *compile time* construct. Once the
code is compiled, it turns a record into a tagged tuple (e.g. {robot,
"Crusher", industrial, [], []}), and turns all of the access of the
record into pattern matches like {robot, _, industrial, _, _}, or
simple element extraction with element/2.

   In order to do this, the compiler needs to know what type of record
it is, *at compile time*. In your example, it's pretty obvious what
kind of record the variable is, but if you are (say) passing that
variable to a function, how would the compiler know which record
definition it should be using? It can't find all of the call sites
where the function is called from, because some of them might be
outside the module being compiled...

   Hugo.

> 
> 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


-- 
Hugo Mills             | I thought I'd discovered a new colour, but it was
hugo@REDACTED carfax.org.uk | just a pigment of my imagination.
http://carfax.org.uk/  |
PGP: E2AB1DE4          |
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: Digital signature
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20161108/9470104c/attachment.bin>


More information about the erlang-questions mailing list