A closure is a function whose body references some variable that is declared in a parent scope.
amount is the free variable. This is because amount is not defined in the lambda, but rather, as is_larger_than’s argument.
Here’s one possible implementation:
| new_db = lambda do |
| db = {} |
| |
| insert = lambda do |artiste, album| |
| db[artist] = album |
| end |
| |
| dump = lambda do |
| db |
| end |
| |
| delete = lambda do |artiste| |
| old = db[artiste] |
| db[artiste] = nil |
| old |
| end |
| |
| {:insert => insert, :dump => dump, :delete => delete} |
| end |
| complement = lambda do |pred| |
| lambda do |args| |
| not pred.call(args) |
| end |
| end |
The main trick here is that the starting value can be anything you want it to be, including an array. In this case, the lambda becomes a mapping function:
| reducer.call([], lambda { |acc, x| acc << x * 2 }, [1, 2, 3, 4, 5]) |