Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a full powered closure?

I was at a Java conference on Scala the other day and the speaker referred to 'full powered closures'. I am having a hard time nailing down a definition that makes sense to me. I have read the wiki page on closures but it really didn't answer it for me. Can someone help me with a clear cut definition? Maybe even include a simple example.

Thanks!

like image 760
northpole Avatar asked Jul 17 '10 15:07

northpole


2 Answers

In computer science, a closure is a first-class function with free variables that are bound in the lexical environment.

You don't need more than this sentence from the wikipedia article. What Java lacks (in addition to the ugly syntax) is the feature of binding free variables from outside the closure. An example:

int x = 0;
new Runnable() {
    public void run() {
        x = 1;
    }
}.run();

Here the Java compiler will complain about the variable x.

The same thing in scala works just fine and is a lot less verbose:

var x = 0
val fun = ()=>{x=1}
fun
like image 146
Kim Stebel Avatar answered Nov 16 '22 02:11

Kim Stebel


Since I feel like a beginner (compared to DPP and Amber) I might explain it to a beginner in a beginners language:

First, anonymous function (or code block/lambda expression) is simply a function that does not have a name. It could be tied to a variable like this.

scala> val foo = (x: Int) => 2*x 
foo: (Int) => Int = <function1>

scala> val bar = foo
bar: (Int) => Int = <function1>

scala> bar(5)
res2: Int = 10

You see, the function doesn't have the name foo, it could be called from bar instead.

Second, a closure is an anonymous function that has a variable that is not defined inside the function (the variable/value must have been declared before the function is defined). The term "full powered closure" might refer to this functionality.

scala> var constant = 7
constant: Int = 7

scala> val foo = (x: Int) => 2*x + constant
foo: (Int) => Int = <function1>

scala> foo(5)
res3: Int = 17

scala> constant = 6
constant: Int = 6

scala> foo(5)
res4: Int = 16

First time you see this, you might wonder what it is good for. In short, it has many sectors of application :-)

like image 26
olle kullberg Avatar answered Nov 16 '22 01:11

olle kullberg