19

I tried to google for "cool Lambda / closure tricks" and variations of the same but didn't get any satisfactory results.

So could you guys please list out some of the Lambda tricks that you know. Please also include examples in your posts if possible. The examples should be preferably in C++ (with C++0x lambda syntax), C# or Ruby.

Thanks! :-)

PS : If you can rephrase this question, please do. It seems like I haven't framed it properly. :(

10

Well, obviously all the standard list functions like filter, map and reduce, which work quite well in combination with each other.

mansions = houses.filter {|house| house.sq_ft > 8000}
total_prices = mansions.map do |mansion|
  mansion.price + mansion.upgrades.map(&:cost).reduce(:+)
end
mansion_list = mansions.zip(total_prices).each_with_index do |mansion, price, i|
  puts "#{i+1}. #{mansion.address} ($#{price})"
end
7

Tying in a simple event

form.Click += (sender, e) => MessageBox.Show("Hi!");
5 accepted

Lambda expressions are awesome to build DSLs.

In Smalltalk even if/else is just a simple DSL. Imagine that you would define the following in Ruby.

class TrueClass
  def if_true
    yield
  end
end

class FalseClass
  def if_true
  end
end

(1 > 2).if_true { puts "should not print" }
(2 > 1).if_true { puts "should print" }

for a more common sense example, take a look at Ruby's CGI module

require 'cgi' 

cgi = CGI.new("html3") # add HTML generation methods 
cgi.out { 
  cgi.html { 
    cgi.head { "\n"+cgi.title{"This Is a Test"} } + 
    cgi.body { "\n"+ 
      cgi.form {"\n"+ 
        cgi.hr + 
        cgi.h1 { "A Form: " } + "\n"+ 
        cgi.textarea("get_text") +"\n"+ 
        cgi.br + 
        cgi.submit 
     } 
   } 
}

(Above example taken from the Pickaxe book).

5

Alternative to strategy pattern, command pattern, other design patterns

There are quite a few design patterns which wrap up a single method with a class, such as:

interface IStrategy
{
    void PrintMsg();
}

class ListPrinter : IStrategy
{
    public void PrintMsg() { Console.WriteLine("ListPrinter"); }
}

class HierarchialPrinter : IStrategy
{
    public void PrintMsg() { Console.WriteLine("HierarchialPrinter"); }
}

class Worker
{
    IStrategy strategy;
    public Woker(IStrategy strategy)
    {
        this.stategy = strategy;
    }

    public void Print()
    {
        strategy.PrintMsg();
    }
}

class Program
{
    public static void Main(string[] args)
    {
        Worker worker = new Worker(new ListPrinter());
        worker.Print();
    }
}

Why wrap a function in an interface and class when we can pass the function directly?

class Worker
{
    Action strategy;
    public Woker(Action strategy)
    {
        this.strategy = strategy;
    }

    public void Print()
    {
        strategy();
    }
}

class Program
{
    public static void Main(string[] args)
    {
        Worker worker = new Worker(() => Console.WriteLine("Awesome"));
        worker.Print();
    }
}
4

javascript:

for(var i; i< links.length; i++)
{
   (function(num){ // <-- closure begins with '('
       // num is namespaced to this closure
       links[num].onclick = function(){
           myFunc(num);
       }
    })(i);// <-- closure ends with ')' and is called by '()'
}

It's incredibly powerful for iterating over a list of items, yet ensuring that when those items execute they have been namespaced to hold values defined at the same time as they were.

the num variable will change for each iteration, but each closure will save the value of any variable defined within it, for any code executed within it.

4
10.times do |i|
    print "#{i} "
end

numbers = [1, 2, 5, 6, 9, 21]

numbers.each do |x|
    puts "#{x} is " + (x >= 3 ? "many" : "few")
end

squares = numbers.map {|x| x * x}

In the above code, times, each and map are the functions that accept code blocks (or lambda expressions, in C# terminology) as their inputs. Because of this idiom, the code becomes far more readable than it would otherwise be.

4

This is not a trick, but a general benefit of lambda expressions. Without lambda expressions, the logic for a bit of code gets spread out. Consider something like:

std::for_each(cont.begin(), cont.end(), doit);

What does that line do? You can't tell without looking at doit() which means you have more work to do to follow the code.

By using lambda expressions, you can bring related logic close together which greatly benefits being able to comprehend code.

3

Yet another one.

In Smalltalk there is not break statement. So to break out of a loop, the entire loop is put into a lamda expression which gets as parameter another lambda expression with a return. Since the return is defined in the method which creates the first lambda expression, calling the second lambda expression will break out of the first one and return from the method.

Again equivalent code in Ruby

def fakeBreak
  yield Proc.new { return }  
end

fakeBreak do |outtahere| 
  (1..100).each do |n|
    puts n
    outtahere.call if n == 20
  end
end
2

Not all of them, but here is one in Python:

>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
>>> sorted(L, key=lambda x:x[1])
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
2

Not typically lambda expressions directly, but closely related:

LINQ uses it extensively, note that the lambda syntax is implied in the simple form

from row in database
where row.id == 12
select row.name

Which is equivalent to

database.Where(row => row.id == 12).Select(row => row.name)

Try writing that out without using extension methods or lambdas and you end up with about 200 characters or so.

2

One cool trick (at least in Ruby) is that you can use everything as lambda expression.

Well, everything that implements to_proc. So if you define that in Symbol you can use symbols as lambda expressions. (In Ruby 1.9 this is part of the core, amirite?)

class Symbol
  def to_proc
    lambda { |receiver,*args| receiver.send(self,*args) }
  end
end

array = %w{The quick brown fox jumps over a lazy dog}.collect(&:size)

yields

[3, 5, 5, 3, 5, 4, 1, 4, 3]

on which we may call

array.inject(0,&:+)

which yields

33
1

Take a look at these:

this_plant = self
       # this wonderful block gets both all the templates within this_plant and each templates attributes!  
       this_plant.get_attributes(:temp) { |template| this_plant.templates << Template.new(template.to_s,this_plant); this_plant.templates.last }


 def get_attributes(type,&block)
    search
    type == :app ? iterate_over = app_attributes[@plant.intern][@env.intern] :
                    iterate_over = temp_attributes[@plant.intern][@env.intern]            

    block ? iterate_over.keys.each do |key|
             plant_object = yield key
             plant_object.attributes = iterate_over[plant_object.name.intern] 

           end :
            iterate_over.keys


end

what these 2 methods do (thanks to the block!) is populate the plant with templates AND populate the templates with attributes all in one line of code (and the get_attributes method of course!)! You can adopt this to populate sophisticated hierarchies is an intuitive and easy manner.

1

this is something i recently used in a project--i needed to return items from a list, either in sequence or randomly (depending on a setting) and looping back to the beginning of the list as necessary.

It's all closures. I could have done it without, but I would have ended up with almost 2x more code and it would have been buggier.

//returns items either sequentially or randomly
//(code is from memory)
class ListEnumerator
{
     public ListEnumerator(List<MyItem> myList, Func<bool> isRandom )
     {
          var index =0;
          var rnd = new Random(); 

          Func<int> nextIndex = () => 
          {                       
              if(isRandom()) 
              { index= rnd.Next(myList.Count - 1); }                        
              else { index = index + 1 % myList.Count; }
          };
          getNext = () =>
          {        
              index = nextIndex(); 
              return myList[index]; 
          };

     }
     readonly Func<MyItem> getNext;
     public MyItem GetNext() { return getNext(); }
}

And in the constructor, I pass in a closure:

var le= new ListEnumerator(lst, () => settings.ListSetting.IsRandom);


Without closures, the ListEnumerator would either have to know about the settings class (more coupling) or I'd need a mediator object (low coupling but more code).

 //like this, coupled to settings class
 public ListEnumerator(List<MyItem> lst, Settings s)

or

 //with a mediator object (and it would end up needing to implement an interface)
 interface IListEnumeratorSettings { bool IsRandom; }

 class ListEnumeratorSettings : IListEnumeratorSettings
 {
       Settings settings;
       public bool IsRandom { get { return s.ListSettings.IsRandom;}}
       public ListEnumeratorSettings(Settings s) {settings = s;}
 }
 // and
 public ListEnumerator(List<MyItem> lst, IListEnumeratorSettings s) {...}

The closure accomplishes the same thing as me writing a mediator object, except with the closure, the compiler creates the mediator object behind the scenes, so it's less code you have to test.