亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Backend Development Python Tutorial For loops and comprehensions in Elixir - transforming imperative code

For loops and comprehensions in Elixir - transforming imperative code

Dec 04, 2024 pm 03:05 PM

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 <- represents a 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 <- [1, 2, 3, 4, 5], do: n ** 2

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

[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 <- [1, 2, 3, 4, 5], rem(n, 2) == 0, do: n ** 2

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:

[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 of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How to handle API authentication in Python How to handle API authentication in Python Jul 13, 2025 am 02:22 AM

The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

Explain Python assertions. Explain Python assertions. Jul 07, 2025 am 12:14 AM

Assert is an assertion tool used in Python for debugging, and throws an AssertionError when the condition is not met. Its syntax is assert condition plus optional error information, which is suitable for internal logic verification such as parameter checking, status confirmation, etc., but cannot be used for security or user input checking, and should be used in conjunction with clear prompt information. It is only available for auxiliary debugging in the development stage rather than substituting exception handling.

What are python iterators? What are python iterators? Jul 08, 2025 am 02:56 AM

InPython,iteratorsareobjectsthatallowloopingthroughcollectionsbyimplementing__iter__()and__next__().1)Iteratorsworkviatheiteratorprotocol,using__iter__()toreturntheiteratorand__next__()toretrievethenextitemuntilStopIterationisraised.2)Aniterable(like

What are Python type hints? What are Python type hints? Jul 07, 2025 am 02:55 AM

TypehintsinPythonsolvetheproblemofambiguityandpotentialbugsindynamicallytypedcodebyallowingdeveloperstospecifyexpectedtypes.Theyenhancereadability,enableearlybugdetection,andimprovetoolingsupport.Typehintsareaddedusingacolon(:)forvariablesandparamete

How to iterate over two lists at once Python How to iterate over two lists at once Python Jul 09, 2025 am 01:13 AM

A common method to traverse two lists simultaneously in Python is to use the zip() function, which will pair multiple lists in order and be the shortest; if the list length is inconsistent, you can use itertools.zip_longest() to be the longest and fill in the missing values; combined with enumerate(), you can get the index at the same time. 1.zip() is concise and practical, suitable for paired data iteration; 2.zip_longest() can fill in the default value when dealing with inconsistent lengths; 3.enumerate(zip()) can obtain indexes during traversal, meeting the needs of a variety of complex scenarios.

Python FastAPI tutorial Python FastAPI tutorial Jul 12, 2025 am 02:42 AM

To create modern and efficient APIs using Python, FastAPI is recommended; it is based on standard Python type prompts and can automatically generate documents, with excellent performance. After installing FastAPI and ASGI server uvicorn, you can write interface code. By defining routes, writing processing functions, and returning data, APIs can be quickly built. FastAPI supports a variety of HTTP methods and provides automatically generated SwaggerUI and ReDoc documentation systems. URL parameters can be captured through path definition, while query parameters can be implemented by setting default values ??for function parameters. The rational use of Pydantic models can help improve development efficiency and accuracy.

How to test an API with Python How to test an API with Python Jul 12, 2025 am 02:47 AM

To test the API, you need to use Python's Requests library. The steps are to install the library, send requests, verify responses, set timeouts and retry. First, install the library through pipinstallrequests; then use requests.get() or requests.post() and other methods to send GET or POST requests; then check response.status_code and response.json() to ensure that the return result is in compliance with expectations; finally, add timeout parameters to set the timeout time, and combine the retrying library to achieve automatic retry to enhance stability.

Setting Up and Using Python Virtual Environments Setting Up and Using Python Virtual Environments Jul 06, 2025 am 02:56 AM

A virtual environment can isolate the dependencies of different projects. Created using Python's own venv module, the command is python-mvenvenv; activation method: Windows uses env\Scripts\activate, macOS/Linux uses sourceenv/bin/activate; installation package uses pipinstall, use pipfreeze>requirements.txt to generate requirements files, and use pipinstall-rrequirements.txt to restore the environment; precautions include not submitting to Git, reactivate each time the new terminal is opened, and automatic identification and switching can be used by IDE.

See all articles