obsessed with anonymous functions

Any normal person would just live without anonymous functions in PHP, they are buggy and non trivial ones are pain to write and read. I’m not sure why I seam to obsess over them.

At the very least, the below code will test unicode in your dev tools :)

Edit: Of course after I wrote that I discovered that Wordpress was ignoring the λ character. A little fix from here and everything is working again.

<?php

    // Create an 'anonymous' function without specifying arguments.
    // Arguments are considered to be named $a to $z
    function λ($body)
    {
        $args = '';
        if(preg_match_all('#(\$[a-z])\b#', $body, $matches, PREG_SET_ORDER) !== 0)
        {
            $allArgs = array();
            foreach($matches as $match)
            {
                $allArgs[] = $match[1];
            }
            $allArgs = array_unique($allArgs);
            sort($allArgs);
            $args = implode(',', $allArgs);
        }
       
        // Make sure it's terminated (we don't care about extra trailing ';')
        return create_function($args, $body . ';');
    }
   
   
    // Creating
    $multiply = λ('return $a * $b');
    echo "23 * 65 = " . $multiply(23, 65) . "\n";
   
    // Only $a to $z are reserved
    $bSquaredByA = λ('$unused = "Hello"; $b_square = $b * $b; return $b_square * $a');
    echo "8 * 6^2 = " . $bSquaredByA(8, 6) . "\n";
   
    // Embedding in strings
    $square      = λ('return $a * $a');
    $numbers     = array(2,4,8);
    foreach($numbers as $num)
    {
      echo "$num * $num = {$square($num)}\n";
    }
   
    // Note you don't have to use $a for your first argument, and $b for your second.  They just
    // Need to be in the right order
    $print_two_things = λ('echo "Second: " . $y . "\n"; echo "First: " . $d . "\n";');
    $print_two_things("Hello", "World!");
   
    // Practical use
    $numbers     = array(1,1,1,2,2,3,3,3,4,5,5,6,7,8,9);
    $above_three = array_filter($numbers, λ('return $x > 3;'));
    echo "Numbers above three =  " . implode(", ", $above_three) . "\n";    

?>

This entry was posted on Wednesday, January 21st, 2009 at 6:30 pm and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “obsessed with anonymous functions”

  1. dingbats Says:

    It’s your inner Pythonista struggling to get OUT.

Leave a Reply