Search code examples
hasherlang

Is it possible to convert an Erlang Atom into a numeric value?


As far as I am aware, atoms in Erlang are stored as indices into the Atom Table, ie they are essentially numbers.

I want to calculate a hash value for a list which contains atoms, so ideally I would want to convert the atoms into numbers for processing. I am aware that the numbers can vary between VMs, but that is not relevant for my use case -- I am just looking for an easy way to convert them into numerical values.

I guess I could convert them back into lists or binaries (but those are then the lists of the characters making up the name) and use those values instead to calculate a hash value (essentially of the name of the atom).

So my questions are:

  1. Is it at all possible to access the internal (numerical) value of an atom?
  2. Should I not worry about this at all and instead use the atom_to_list function, which will probably only be marginally slower?

Solution

  • Not sure if there's a way to access the atom table index, but if you want to get a hash value for an Erlang term, one easy way is erlang:phash2/1:

    > erlang:phash2(foo).
    27999
    

    The hash value is based on the name of the atom, so it's similar to your atom_to_list idea.