concept Reduce in category .net

appears as: Reduce
Concurrency in .NET

This is an excerpt from Manning's book Concurrency in .NET.

This chapter presents MapReduce, one of the most widely used functional programming patterns in software engineering. Before delving into MapReduce, we’ll analyze the declarative programming style that the functional paradigm emphasizes and enforces, using PLINQ and the idiomatic F#, PSeq. Both technologies analyze a query statement at runtime and make the best strategy decision concerning how to execute the query in accordance with available system resources. Consequently, the more CPU power added to the computer, the faster your code will run. Using these strategies, you can develop code ready for next-generation computers. Next, you’ll learn how to implement a parallel Reduce function in .NET, which you can reuse in your daily work to increase the speed of execution of aggregates functions.

Now you’ve learned about the power of aggregate operations, which are particularly suited to scalable parallelization on multicore hardware due to low memory consumption and deforesting optimization. The low memory bandwidth occurs because aggregate functions produce less data than they ingest. For example, other aggregate functions such as Sum() and Average() reduce a collection of items to a single value. That’s the concept of reduction: it takes a function to reduce a sequence of elements to a single value. The PLINQ list extensions don’t have a specific function Reduce, as in F# list comprehension or other functional programming languages such as Scala and Elixir. But after having gained familiarity with the Aggregate function, the implementation of a reusable Reduce function is an easy job. This listing shows the implementation of a Reduce function in two variants. The bold highlights annotated code.

Listing 5.10 Parallel Reduce function implementation using Aggregate
static TSource Reduce<TSource>(this ParallelQuery<TSource> source, 
                                 Func<TSource, TSource, TSource> reduce) =>
ParallelEnumerable.Aggregate(source,   #1  
 (item1, item2) => reduce(item1, item2));   #2  

static TValue Reduce<TValue>(this IEnumerable<TValue> source, TValue seed,
    Func<TValue, TValue, TValue> reduce) =>
    source.AsParallel()
 .Aggregate(   #1  
       seed: seed,
 updateAccumulatorFunc: (local, value) => reduce(local, value),   #2  
       combineAccumulatorsFunc: (overall, local) => 
 reduce(overall, local),   #3  
 resultSelector: overall => overall);   #4  

int[] source = Enumerable.Range(0, 100000).ToArray();
int result = source.AsParallel()
 .Reduce((value1, value2) => value1 + value2);  #5  

#1   Uses a function to determinate if a number is prime
#2   For each iteration, the function func is applied to the current item, and the previous value is used as an accumulator.
#3   Combines intermediates results from each thread (partition result)
#4   Returns the final result; in this place you could have a transformation against the output.
#5   Uses the Reduce function, passing an anonymous lambda to apply as a reducing function


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":36},{\"line\":0,\"ch\":49}],[{\"line\":2,\"ch\":0},{\"line\":2,\"ch\":18}],[{\"line\":7,\"ch\":11},{\"line\":7,\"ch\":21}],[{\"line\":16,\"ch\":20},{\"line\":16,\"ch\":30}],[{\"line\":7,\"ch\":11},{\"line\":7,\"ch\":21}],[{\"line\":16,\"ch\":20},{\"line\":16,\"ch\":30}]]"}
!@%STYLE%@!

The first Reduce function takes two arguments: the sequence to reduce and a delegate (function) to apply for the reduction. The delegate has two parameters: the partial result and the next element of the collection. The underlying implementation uses Aggregate to treat the first item from the source sequence as an accumulator.

The second variant of the Reduce function takes an extra parameter seed, which is used as the initial value to start the reduction with the first value of the sequence to aggregate. This version of the function merges the results from multiple threads. This action creates a potential dependency on both the source collection and the result. For this reason, each thread uses thread-local storage, which is non-shared memory, to cache partial results. When each operation has completed, the separate partial results are combined into a final result.

updateAccumulatorFunc calculates the partial result for a thread. The combine­AccumulatorsFunc function merges the partial results into a final result. The last parameter is resultSelector, which is used to perform a user-defined operation on the final results. In this case, it returns the original value. The remainder of the code is an example to apply the Reduce function to calculate the sum of a given sequence in parallel.

Figure 5.6 A schematic illustration of the phases of a MapReduce computation. The MapReduce pattern is composed primarily of two steps: map and reduce. The Map function is applied to all items and produces intermediate results, which are merged using the Reduce function. This pattern is similar to the Fork/Join pattern because after splitting the data in chunks, it applies in parallel the tasks map and reduce independently. In the image, a given data set is partitioned into chunks that can be performed independently because of the absence of dependencies. Then, each chunk is transformed into a different shape using the Map function. Each Map execution runs simultaneously. As each map chunk operation completes, the result is passed to the next step to be aggregated using the Reduce function. (The aggregation can be compared to the join step in the Fork/Join pattern.)

c05-06.png