nicbet

nicbet

Collection of Elixir Language Idioms

Introduction

Now that the language is picking up support and maturing nicely, I’d like to start a collection of common and recurring Elixir language idioms - recurring expressions or constructs in Elixir code that are not built-in features of the language.

What is a Language Idiom?

Consider this: in English one would usually say "the small black cat", even though grammar rules definitely deem "the black small cat" a fully valid language construct.

When studying a language you may be good at learning the vocabulary (syntax) and catching on with the grammar, but you may fail to properly express yourself in that language. For instance, many English speakers learning Polish struggle trying to use English thoughts and then translating them to Polish. Even though they know all the right translations of those words, and the rules in which to order them, the end result is incomprehensible. Polish is a highly idiomatic language.

In a similar fashion, programming languages tend to have idioms - commonly used patterns that form an implicit agreement of the community on how to describe certain expressions/task/algorithms in a particular programming language.

Language idioms are commonly an indicator of the flexibility of a language - the more flexible a language is and the less rigid the rules are, the more equivalent ways tend to exist in coding tasks, algorithms and data structures that achieve the same result. For instance, languages like Perl, or Scala are sometimes called idiomatic languages - there exist dozens of idioms within these languages, whereas a language like Java does not seem to have many idioms.

Like many functional languages, Elixir has a surprising level of expressive power, allowing for high levels of succinctness in the programs we write. At the same time, it makes learning the language harder for new-comers as Elixir forces us to adopt Elixir’s way of expressing our thoughts and ideas in code.

Why should I care?

There are several benefits in establishing language idioms within a community, and being familiar with language idioms as learners of the language.

  • When reading code that someone else wrote, recognizing several lines of code as an idioms allows the reader to mentally file those lines into a particular corner (“loop iterating over all elements and calculating a sum!”). This allows us to reason and understand code on a more abstract level, without having to carefully read and comprehend each single line of code individually.

  • When writing code on your own, you won’t have to re-invent the wheel. Familiarity with Elixir idioms will allow you to be productive quickly without having to put in too much thought on how to achieve the same re-curring tasks over and over again. (“Uhm, how did I sort that Map last time by key-order?”).

Elixir Language Idiom Collection

Function calls return Tuples indicating Success/Error

  • Functions return tuples based on success status
  • The first element of this tuple is usually :ok on success, and :error on (any kind of) failure.
  • Callers pattern-match against the success and error cases

Example

defmodule HelloPhoenix.RoomChannel do
  use Phoenix.Channel

  def join("room:lobby", _message, socket) do
    {:ok, socket}
  end
  def join("room:" <> _private_room_id, _params, _socket) do
    {:error, %{reason: "unauthorized"}}
  end
end

Other Languages with this idiom

Python, Swift


What other Elixir idioms did you observe in your own code, or in others’ Elixir code so far?

Most Liked

AstonJ

AstonJ

Nice - I’ve made this into a wiki for you :023:

You can find more details about our wikis here: How to post or use our wikis

But in short,

  • Anyone at Trust Level 1 can edit a wiki (wiki owner gets notified of edits)
  • People usually post stuff as normal in the thread - and the wiki owner usually decides whether to include it in the first post (the ‘wiki’). However as mentioned anyone at TL1 can add stuff to the wiki if they feel it should be included.

Any questions just let me know.

nicbet

nicbet

Great suggestion! I’ve expanded the introduction section with some examples.

sashaafm

sashaafm

May I suggest you add a section where you explain what an idiom is? I think it makes it friendlier and more accessible to beginners :slight_smile:

elbrujohalcon

elbrujohalcon

There many idioms already written at Programming Idioms

Where Next?

Popular in Wikis Top

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
georgeguimaraes
Hi people, since the new year is coming, I’d like to plan my travels for events in 2017. So, what events (Elixir or FP related) that you...
New
Rich_Morin
I’d like to start a discussion of data serialization formats, in the context of Elixir. The rest of this note is a combination of persona...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
OvermindDL1
It was stated at https://github.com/elixir-lang/elixir/issues/6172 that Mirrors of the primary Elixir website would be useful since Cloud...
New
anildigital
Here is list of plugins for different editors Sublime Text 3 — Elixir.tmbundle - https://github.com/elixir-editors/elixir-tmbundle/#co...
New
blackode
This is a wiki - anyone at Trust Level 1 or higher can help keep it updated. Elixir Pocket Syntax Uncommon Logical stuff of Elixir modul...
New
gmile
:httpc HTTP client is part of Erlang standard library, and as such can be easily used in Elixir code too. One particular advantage of usi...
New
shavit
To transcode the video there is FFMPEG. On Demand When a user uploads a video, the app renames and copy the file to a path, then call F...
New

Other popular topics Top

lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
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