Skip to content

Instantly share code, notes, and snippets.

@remram44
Last active December 18, 2015 19:39
Show Gist options
  • Select an option

  • Save remram44/5834233 to your computer and use it in GitHub Desktop.

Select an option

Save remram44/5834233 to your computer and use it in GitHub Desktop.
Closures (2)
#include <functional>
#include <iostream>
#include <vector>
int main()
{
std::vector<std::function<int (int)>> l;
for(int i = 0; i < 10; ++i)
l.push_back([=](int x) mutable { return i += x; });
std::cout << l[2](3) << ", "; // 5
std::cout << l[2](4) << ", "; // 9
std::cout << l[4](2) << std::endl; // 6
return 0;
}
package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
fmt.Printf("%d ", i)
wg.Done()
}()
}
wg.Wait() // 10 10 10 10 10 10 10 10 10 10
}
l = {}
for i = 0, 10 do
l[i] = function(x)
i = i + x
return i
end
end
print(l[2](3)) -- 5
print(l[2](4)) -- 9
print(l[4](2)) -- 6
l= []
for i in xrange(10):
def anonym(x, i=i):
i += x
return i
l.append(anonym)
print l[2](3) # 5
print l[2](4) # 6
print l[4](2) # 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment