Fill in some more docs.

This commit is contained in:
Bob Nystrom
2015-01-01 18:48:59 -08:00
parent 0882897c6b
commit 8ab91bf6c2
8 changed files with 29 additions and 17 deletions
+4 -4
View File
@@ -1,7 +1,7 @@
^title Functions
^category types
No self-respecting language today can get by without functions—first class little bundles of code. Since Wren is object-oriented, most of your code will live in methods on classes, but free-floating functions are still useful.
No self-respecting language today can get by without functions—first class little bundles of code. Since Wren is object-oriented, most of your code will live in methods on classes, but free-floating functions are still eminently handy.
Functions are objects like everything else in Wren, instances of the `Fn` class.
@@ -9,7 +9,7 @@ Functions are objects like everything else in Wren, instances of the `Fn` class.
Most of the time you create a function just to pass it to some method. For example, if you want to filter a [list](lists.html) by some criteria, you'll call its `where` method, passing in a function that defines the predicate you're filtering on.
Since that's the most common usage pattern, Wren's syntax optimizes for that. Taking a page from Ruby, a function is created by passing a *block argument* to a method. At it's simplest, it looks like this:
Since that's the most common usage pattern, Wren's syntax optimizes for that. Taking a page from Ruby, a function is created by passing a *block argument* to a method. At its simplest, it looks like this:
:::dart
blondie.callMe {
@@ -106,7 +106,7 @@ Otherwise, the body returns `null` by default. You can explicitly return a value
## Closures
As you expect, functions are closures: they can access variables defined outside of their scope. They will hold onto closed-over variables even after leaving the scope where the function is defined:
As you expect, functions are closures—they can access variables defined outside of their scope. They will hold onto closed-over variables even after leaving the scope where the function is defined:
:::dart
class Counter {
@@ -116,7 +116,7 @@ As you expect, functions are closures: they can access variables defined outside
}
}
Here, the `create` method returns the function created on its second line. That function references a variable `i` declared outside of the function. Even after the function is returned from `create`, it is still able to access `i`.
Here, the `create` method returns the function created on its second line. That function references a variable `i` declared outside of the function. Even after the function is returned from `create`, it is still able to read and assign to`i`:
:::dart
var counter = Counter.create