1

I'm a big fan of 1tbs when it comes to c-like languages. Now that php got decent lambdas and closures, though, I'm not sure the style I'm using for them (fundamentally made up, has something to do with the jquery source code) is the most readable/standard option. What do you think? Somebody has some nice examples of 1tbs + lambdas and functions as parameters?

Here's a sample of my code.

function bold_search_terms($needle, $haystack) {
  return str_replace(
     $occurrencies = array_filter (
         explode(" ",$haystack),
         function ($var) use ($needle) {
            return(levenshtein($var, $needle) < 3);
         }
     ),
     array_map(
          function ($var) {
              return "<strong>$var</strong>";
          },
          $occurrencies
     ),
     $haystack
  );
}

2 Answers 2

1

I'm not a big fan of inserting lambdas in that way when they have to span multiple lines. Unfortunately PHP is quite verbose in this, needing

function($something) use ($something_else) { }

as opposed to - for example - Perl's

sub { }

where parameters and enclosed variables are assumed/detected by scope, allowing a lot more lambdas to fit in one single line.

At the end of the day it comes down to personal taste, in this case I'd break the function in parts and apply str_replace() to precalculated values.

1

If you like it a bit more concise, take some inspiration from Lisp:

function bold_search_terms($needle, $haystack) {
    return str_replace
        ($occurrences = array_filter
            (explode(" ", $haystack),
            function ($var) use ($needle)
                { return(levenshtein($var, $needle) < 3); }),
        array_map
            (function ($var)
                { return "<strong>$var</strong>"; },
            $occurrences),
        $haystack);
}

Indentation and newlines show the tree of parameters. Your solution is eminently readable as-is, though.

2
  • I like the pretty print style as well, but I'm afraid this solution would be too different in looks from the rest of the code. Maybe when I'll decide to go completely functional with php - and get fired - I'll adopt it. Commented Apr 7, 2011 at 10:37
  • still, it looks so elegant... damn! Commented Apr 7, 2011 at 10:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.