search
HomeBackend DevelopmentPython TutorialFor loops and comprehensions in Elixir - transforming imperative code

For loops and comprehensions in Elixir - transforming imperative code

In this article, we’ll cover some common uses of for loops and comprehensions in Python, how to analyze an existing loop, and how to transform them into their equivalent expressions in Elixir, using the functions in the Enum module and comprehensions.

We’ll focus on:

  • transforming a collection of data through a function (map)
  • filtering values into or out of a collection (filter)
  • producing a single aggregate value or structure, such as an average (reduce or fold)

We’ll finish off with a basic example that combines all three!

Python

For loops

In Python, for loops typically feature interleaved processing - the steps are combined together into the same clause or body. Here’s an example that squares the first two even numbers:

result = 0
for num in [1, 2, 3, 4, 5]:
    if num % 2 == 0:
        result += num ** 2
print(result)  # Output: 20

One challenge of this interleaved body is to:

  1. identify each step, and…
  2. work out what type of step it is.

Breaking apart each step allows you to understand the transformations taking place, eliminate any unnecessary ones, and rewrite those steps into another language construct or higher-level function.

Annotating the function above results in:

result = 0
for num in [1, 2, 3, 4, 5]:
    ## Filter
    if num % 2 == 0:
        ## Reduce (result += ) and Map (num ** 2)
        result += num ** 2
print(result)  # Output: 20

The steps

As a result - the order of steps are:

  1. Filter “out” odd numbers/”in” even numbers
  2. Map numbers (e.g. 2) to their corresponding square number (e.g. 4)
  3. Reduce to a sum of the squared even numbers

Comprehensions

Comprehensions in Python are simple ways to map and filter collections like lists and dictionaries. They don’t offer a way to reduce the result, but we can use built-in functions like sum to transform the above to process the result of the comprehension:

result = sum(num ** 2 for num in [1, 2, 3, 4, 5] if num % 2 == 0)
print(result)  # Output: 20

With comprehensions, the expression divides the map step (num ** 2) and filter step (if num % 2 == 0) clearly. sum is the reduce step here.

It’s easy to skim through these comprehension expressions in Python, and it places a useful upper limit on the complexity of a comprehension.

With this background, and a better understanding of the structure and limitations of Python’s processing constructs, let’s proceed to rewriting the above Python code using Elixir’s comprehensions and Enum pipelines!

Mapping: Enum.map and generators

How can we write the step to square numbers? In Elixir, it’s simple!

Using Enum.map:

result = 0
for num in [1, 2, 3, 4, 5]:
    if num % 2 == 0:
        result += num ** 2
print(result)  # Output: 20

and using comprehensions (for):

result = 0
for num in [1, 2, 3, 4, 5]:
    ## Filter
    if num % 2 == 0:
        ## Reduce (result += ) and Map (num ** 2)
        result += num ** 2
print(result)  # Output: 20

The generator expression, generating values to be used in the body of the for expression, after do:

Filtering: Enum.filter and filters

Easy to do with Enum.filter (or Enum.reject):

result = sum(num ** 2 for num in [1, 2, 3, 4, 5] if num % 2 == 0)
print(result)  # Output: 20

We’ll want to filter out odd numbers before they are squared, so we place it in the right place in the pipeline - before Enum.map.

Using comprehensions, we can add a second expression to the head of the comprehension, a filter, which is a boolean test:

Enum.map([1, 2, 3, 4, 5], & &1 ** 2)

The rem(n, 2) == 0 expression then discards any elements that return false (or nil), leaving [2, 4] as the numbers that are actually passed to the body (do: n ** 2) of the comprehension.

Reduce -> Enum.reduce and reduce:

Using Enum.reduce/2, we can convert a list of squared numbers into their sum by adding to an accumulator. The first element is used as the initial value of the accumulator if we don’t specify an initial value for the accumulator (Enum.reduce/3), and that’s handy here:

for n 



<p>With comprehensions, we have even more power than the Python equivalent. We can add a reduce step by adding another clause to the head:<br>
</p>

<pre class="brush:php;toolbar:false">[1, 2, 3, 4, 5]
|> Enum.filter(& rem(&1, 2) == 0)
|> Enum.map(& &1 ** 2)

making two changes here:

  1. adding a reduce: 0 clause to the head, to specify that we will accumulate a value whose initial value is 0
  2. changing the for body to capture an acc value (the accumulator) that we can add the current squared value to.

Built-in functions: Enum.sum

As a general rule, we should express the data we want to transform in the highest-level way possible. It’s useful to think of Enum.reduce as the lowest level functional transformation, since all other data processing can be rewritten in terms of it.

The Enum module contains plenty of higher-level functions, typically involving reducing a list of values to a single aggregate value, like a sum, maximum or minimum. In this case, we’d like the sum of the elements.

For Enum pipelines, this is straightforward:

for n 



<p>There is not a way to represent these high-level aggregate functions in comprehensions, so we can pipe the output of the comprehension into a Enum.sum call like so, similar to how we did in Python:<br>
</p>

<pre class="brush:php;toolbar:false">[1, 2, 3, 4, 5]
|> Enum.filter(& rem(&1, 2) == 0)
|> Enum.map(& &1 ** 2)
|> Enum.reduce(& &1 + &2)

Mixing different forms should generally be avoided, especially if the transformation is a simple one, as it results in less mental load for the reader - the reduce: form above is actually clearer to read despite being lower-level.

Which Elixir expression is better?

To summarise, we’ve ended up with two forms which could be considered idiomatic. For Enum pipelines:

result = 0
for num in [1, 2, 3, 4, 5]:
    if num % 2 == 0:
        result += num ** 2
print(result)  # Output: 20

and comprehensions:

result = 0
for num in [1, 2, 3, 4, 5]:
    ## Filter
    if num % 2 == 0:
        ## Reduce (result += ) and Map (num ** 2)
        result += num ** 2
print(result)  # Output: 20

Easy to read code should be straightforward to scan through, without ambiguity or stumbling over expressions. I think both forms fill that criteria, as:

  1. they follow a single consistent form - either Enum pipelines or comprehensions
  2. each expression corresponds to a single processing step
  3. it can be read top-to-bottom or left-to-right without interruption

Conclusion

Writing these transformations can be done in several different ways in Elixir, and it is easy for a codebase to vary styles, especially as code is changed and processing becomes more complicated over time.

PureType can break down and analyze Enum pipelines and comprehensions to represent them in their clearest and most idiomatic form, learning your preferences and increasing your code’s readability and clarity for others on the team. Try it out today!

The above is the detailed content of For loops and comprehensions in Elixir - transforming imperative code. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is Python Switch Statement?What is Python Switch Statement?Apr 30, 2025 pm 02:08 PM

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

What are Exception Groups in Python?What are Exception Groups in Python?Apr 30, 2025 pm 02:07 PM

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

What are Function Annotations in Python?What are Function Annotations in Python?Apr 30, 2025 pm 02:06 PM

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.

What are unit tests in Python?What are unit tests in Python?Apr 30, 2025 pm 02:05 PM

The article discusses unit tests in Python, their benefits, and how to write them effectively. It highlights tools like unittest and pytest for testing.

What are Access Specifiers in Python?What are Access Specifiers in Python?Apr 30, 2025 pm 02:03 PM

Article discusses access specifiers in Python, which use naming conventions to indicate visibility of class members, rather than strict enforcement.

What is __init__() in Python and how does self play a role in it?What is __init__() in Python and how does self play a role in it?Apr 30, 2025 pm 02:02 PM

Article discusses Python's \_\_init\_\_() method and self's role in initializing object attributes. Other class methods and inheritance's impact on \_\_init\_\_() are also covered.

What is the difference between @classmethod, @staticmethod and instance methods in Python?What is the difference between @classmethod, @staticmethod and instance methods in Python?Apr 30, 2025 pm 02:01 PM

The article discusses the differences between @classmethod, @staticmethod, and instance methods in Python, detailing their properties, use cases, and benefits. It explains how to choose the right method type based on the required functionality and da

How do you append elements to a Python array?How do you append elements to a Python array?Apr 30, 2025 am 12:19 AM

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function