Best practices of comprehensions in Elixir

Click for: original source

Surprising examples of using for-comprehension in Elixir. For comprehension provides a very elegant syntax to loop over collections and an effective way to transform the given enumerable. By Kamil Lelonek.

A special for form gives you syntactic sugar to iterate, filter, and map the given structures. The entire expression consists of three parts:

  • generators — produce the data for comprehension. Usually, from an enumerable like a list, a map, a range, or even a bitstring. In the form of: element <- collection
  • filters — select only particular elements from an enumerable based on the given condition. In the shape of a function, e.g. x > 2, any_function(element), or even anonymous_function(element)
  • collectables — the result of comprehension. Data structures that implement the Collectable protocol, a list by default

Apart from the answer on what are the elixir comprehensions question, the article also provides robust information on Generators. Generators produce values to be used in comprehension. Any enumerable can be given on the right side, and the left side is used to catch a single element. The article goes over useful tricks to use with generators, including pattern matching, skipping, ignoring … Good read!

[Read More]

Tags programming erlang elixir apis