sodapopcan

sodapopcan

Why does `elem/2` exist?

I’ve been in the Elixir world for five years—not super long but also not super short. In this time I have seen lots of code that uses elem/2 but not once have I ever seen a situation where it made code clearer and in fact has always made code less clear. It seems its main use it to “not break pipelines.” To put it lightly: this is a non-goal. I have never run into a situation where pattern matching isn’t way way way waaaaaaaay clearer than elem/2, even if it means breaking the pipe.

IMO if we ever see an Elixir 2.0 this function should be removed from the language. But please tell me why elem/2 is indispensable to your Elixir work! I realize I’m using very dismissive language but I’m genuinely curious if there is a good use-case for it I’ve never thought of.

Marked As Solved

zachallaun

zachallaun

An example from a project I contribute to: Lexical.Document.Lines

The key insight is that a tuple provides O(1) access to any of its elements, whereas a list is O(n). So if you need a data structure that provides fast access to any arbitrary line of a document, you reach for a tuple. (And then you use elem/2 for access, since you don’t know what its length will be.)

Also Liked

dorgan

dorgan

  • You have tuples, a fixed size array of elements.
  • You can access them by a random index.
  • There is no syntax to access a random index of a tuple
  • Pattern matching requires you to know the length of the tuple up-front

I think it makes sense to have such a function be part of the standard library. The reasoning is quite simple: if you provide a builtin data structure, it makes sense to provide an API to read and write to it.

Wether or not it’s idiomatic to access a random element of a tuple is a whole different topic.

15
Post #3
dimitarvp

dimitarvp

Agreed, but it has to be noted that then – which solves the problem of not breaking pipelines – was only added in Elixir 1.12.

Use then.

sodapopcan

sodapopcan

Everyone is always free to go off topic in any thread I create :sweat_smile:

LostKobrakai

LostKobrakai

It’s main use is accessing a tuple value using an index, which works no matter the size of tuple and in context, where pattern matching is not an option. Just like there’s :erlang.map_get for maps, because pattern matching is not enough.

There’s places in OTP, where you might get differently sized tuples, where leading parts of them contain the same data. You can use elem/2 to select the common fields without needing to know which specific tuple you got if the differenciation doesn’t matter for the code. It also means your code doesn’t break if OTP decides to add another version of tuple with yet another additional datapoint added to the end.

If flag timestamp, strict_monotonic_timestamp, or monotonic_timestamp is specified, the first tuple element is trace_ts instead, and the time stamp is added as an extra element last in the message tuple.

https://www.erlang.org/doc/apps/kernel/trace.html#process/4

Usually one would likely use maps for such a usecase, but sticking to tuples for performance sensitive calls like around tracing is also a good idea.

Also e.g. elixir’s record handling code wouldn’t be a lot more complex macro magic without having such functionality. Technically it doesn’t use Kernel.elem/2, but it optimizes by calling :erlang.element/2 directly, which is also what Kernel.elem/2 is using.

al2o3cr

al2o3cr

Short short version: elem/2 exists because typing :erlang.element is too many characters.

Record also provides some examples of places where elem (or it’s Erlang equivalent) are useful, for instance is_record?:


My interpretation of the release notes about setelement optimizations is that sequences like this one (also from Record) may get a boost from the compiler and/or JIT:

Since the intermediate tuples don’t escape the function, the reduce could do all the mutation in-place.

Where Next?

Popular in Questions Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
Phillipp
Hey, I have a NanoPi-M3 and try to install Elixir on their Ubuntu image. I followed the Raspberry Pi installation instructions from the ...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New

Other popular topics Top

yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

We're in Beta

About us Mission Statement