import multiprocessing
from functools import reduce

def map_function({{ loop_var }}):
    {{ body }}
    return result

def reduce_function(results):
    return reduce(lambda x, y: x + y, results)

if __name__ == '__main__':
    # Determine number of processors
    num_procs = multiprocessing.cpu_count()
    
    # Get data from the iteration expression
    data = {{ iter_expr }}
    
    # Create process pool
    with multiprocessing.Pool() as pool:
        # Map phase: Process data elements in parallel using SIP
        mapped_results = pool.map(map_function, data)
        
        # Reduce phase: Combine results using a tree-based reduction for better performance
        while len(mapped_results) > 1:
            # Pair up results and reduce them in parallel
            pairs = [(mapped_results[i], mapped_results[i+1]) 
                    for i in range(0, len(mapped_results)-1, 2)]
            if len(mapped_results) % 2 == 1:
                pairs.append((mapped_results[-1],))
            
            # Reduce pairs in parallel
            mapped_results = pool.map(lambda p: p[0] if len(p) == 1 else reduce_function(p), pairs)
        
        final_result = mapped_results[0] if mapped_results else None
    
    print(f"Final result: {final_result}")

