Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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
  );
}
share|improve this question

2 Answers 2

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.

share|improve this answer

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.

share|improve this answer
    
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. –  cbrandolino Apr 7 '11 at 10:37
    
still, it looks so elegant... damn! –  cbrandolino Apr 7 '11 at 10:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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