ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Elixir Stream Transformations with Map and Filter

Elixir

Goal -- WPM

Ready
Exercise Algorithm Area
1defmodule StreamProcessor do
2require Logger
3
4@doc """
5Processes a stream of numbers, performing transformations.
6"""
7def process_stream(stream) do
8stream
9|> Stream.map(&transform_initial/1)
10|> Stream.filter(&filter_intermediate/1)
11|> Stream.map(&transform_final/1)
12|> Enum.to_list()
13end
14
15# First transformation: Double the number and add 1
16defp transform_initial(number) do
17Logger.debug("Initial transform: #{number} -> #{number * 2 + 1}")
18number * 2 + 1
19end
20
21# Intermediate filter: Keep only odd numbers greater than 5
22defp filter_intermediate(number) do
23is_odd = rem(number, 2) != 0
24is_greater_than_5 = number > 5
25result = is_odd && is_greater_than_5
26Logger.debug("Filter intermediate: #{number} -> #{result}")
27result
28end
29
30# Final transformation: Conditional mapping
31# If number is even, square it. If odd, add 10.
32defp transform_final(number) do
33Logger.debug("Final transform: #{number}")
34if rem(number, 2) == 0 do
35result = number * number
36Logger.debug(" Even: #{number} -> #{result}")
37result
38else
39result = number + 10
40Logger.debug(" Odd: #{number} -> #{result}")
41result
42end
43end
44
45@doc """
46Helper function to generate a sample stream.
47"""
48def sample_stream(count) do
49Stream.take(Stream.cycle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), count)
50end
51end
52
53defmodule StreamProcessor.Application do
54use Application
55
56def start(_type, _args) do
57# In a real application, you might start supervisors here.
58# For this example, we'll just demonstrate the stream processing.
59IO.puts("Starting StreamProcessor Application...")
60
61# Example Usage:
62IO.puts("Processing sample stream...")
63sample_data = StreamProcessor.sample_stream(20)
64processed_data = StreamProcessor.process_stream(sample_data)
65IO.puts("Processed data: #{inspect(processed_data)}")
66
67{:ok, self()}
68end
69end
Algorithm description viewbox

Elixir Stream Transformations with Map and Filter

Algorithm description:

This Elixir code demonstrates advanced stream processing using Elixir's `Stream` module. It chains multiple transformations: an initial mapping to modify each element, a filtering step to select specific elements, and a final conditional mapping based on the element's properties. Streams are lazy, meaning transformations are applied only when elements are consumed (e.g., by `Enum.to_list/1`). This approach is memory-efficient for large datasets as it processes elements one by one rather than loading everything into memory at once.

Algorithm explanation:

The `StreamProcessor.process_stream/1` function takes an Elixir `Stream` as input and applies a sequence of transformations using the pipe operator (`|>`). The first transformation, `Stream.map(&transform_initial/1)`, doubles each number and adds 1. The second, `Stream.filter(&filter_intermediate/1)`, keeps only numbers that are both odd and greater than 5. The third transformation, `Stream.map(&transform_final/1)`, applies conditional logic: if the number is even, it's squared; if it's odd, 10 is added. Finally, `Enum.to_list/1` consumes the stream, forcing the evaluation of all transformations and collecting the results into a list. The lazy nature of `Stream` ensures that memory usage remains low, as only one element (and its intermediate transformed states) is processed at a time. The `sample_stream/1` function generates a finite stream for demonstration. The time complexity is O(N * T), where N is the number of elements in the stream and T is the average time complexity of the transformations. Since the transformations are O(1) each, the overall time complexity is O(N). The space complexity is O(1) for the stream processing itself (excluding the final list), as only one element is held in memory at any given time during the transformation pipeline.

Pseudocode:

Define a `process_stream` function that accepts a stream.
Pipe the stream through a series of transformations:
  1. `Stream.map(&transform_initial/1)`:
     For each element, apply `transform_initial`.
     `transform_initial` doubles the number and adds 1.
  2. `Stream.filter(&filter_intermediate/1)`:
     For each element, apply `filter_intermediate`.
     `filter_intermediate` keeps elements that are odd AND greater than 5.
  3. `Stream.map(&transform_final/1)`:
     For each remaining element, apply `transform_final`.
     `transform_final` squares even numbers and adds 10 to odd numbers.
Finally, convert the resulting stream to a list using `Enum.to_list/1`.
Define `transform_initial`, `filter_intermediate`, and `transform_final` helper functions.