How do different programming languages โ€‹โ€‹use closures?

As far as I know, combined with knowledge of others, among the main languages

  • Goal c
  • FROM#
  • Vb.net
  • Java
  • Python
  • ruby
  • Javascript
  • Lisp
  • Perl

have closure and anonymous functions. Normal C / C ++ does not have any of them.

Do closures in these languages โ€‹โ€‹have the same semantics? How important are they for everyday programming?

A bit of background: I read about the new additions to Objective- C that target Apple Grand Central Dispatch, and thought I should find out if there really is only one or different ways to introduce block structures into the language.

+3
4

: ? , ?

.NET- (VB/#) , :

. () - , , .

:

  • .NET: . . - () LINQ-.

  • Python: - lambda vars: expr - .

  • Javascript: - , !

    function f(x) { return x + 1; }
    

    var f = function(x) { return x + 1; }
    
  • Ruby: : .

    array.each do |x|
       # code
    end
    

    - , array#each , (), . #:

    Array.Each(x => {
        // Code
    })
    

, :

# Enclose `i` - Return function pointer
def counter():
    i = 0
    def incr():
        i += 1
        print(i)
    return incr

c = counter()
c() # -> 1
c() # -> 2
c() # -> 3

( Java - , !), , .

+5

Java , ( ), , .

day 1 v1.1, , Java , ( OO) , . , , .

, , , TimerTask , :

 Timer timer = new Timer();

 timer.schedule( new TimerTask() {  // this is like the code block. 
     public void run() {
          System.out.println("Hey!");
     }
 },0);

, "TimerTask() {..." - . , .

TimerTask task = new TimerTask() {
     public void run() {
     }
 };


....
timer.schedule( task , 0 ) ;

, .

- , Java.

: " "

" Java"

+3

, , . Java Python "", "" (, Objective C, ). , :

public static Func<int,int> adderGen(int start) {
    return (delegate (int i) {      // <-- start is captured by the closure
                start += i;         // <-- and modified each time it called
                return start;
            });
}
// later ...
var counter = adderGen(0);
Console.WriteLine(counter(1)); // <-- prints 1
Console.WriteLine(counter(1)); // <-- prints 2
// :
// :

, , , # ( ) . , , , , ...

var adders = new List<Func<int,int>>();

for(int start = 0; start < 5; start++) {
    adders.Add(delegate (int i) {
        start += i;
        return start;
    });
}

Console.WriteLine(adders[0](1)); // <-- prints 6, not 1
Console.WriteLine(adders[4](1)); // <-- prints 7, not 5

start 5 , start++ 5 for. , Java Python - , , , , . .

, Perl .

+2

Java , , .

Competing suggestions were made for adding closures to the language in the next version of Java, but none of them were included in the list of official changes.

0
source

Source: https://habr.com/ru/post/1717676/


All Articles