Now it’s time to work that gray matter! Do the following exercises to be sure you have grasped the concepts that were presented in this chapter. Don’t skip this!
What is the definition of a closure?
Identify the free variable in the following:
| def is_larger_than(amount) |
| lambda do |a| |
| a > amount |
| end |
| end |
Here’s an example run:
| >> larger_than_5 = is_larger_than(5) |
| |
| >> larger_than_5.call(4) |
| => false |
| |
| >> larger_than_5.call(5) |
| => false |
| |
| >> larger_than_5.call(6) |
| => true |
You work in a music store and you’ve been tasked with writing a miniature database to store artists and album titles. The database should be able to insert, delete, and list entries, but you cannot use objects other than arrays and hashes. Only lambdas are allowed. Here’s the API:
| >> db = new_db.call |
| |
| >> db[:insert].call("Eagles", "Hell Freezes Over") |
| => Hell Freezes Over |
| |
| >> db[:insert].call("Pink Floyd", "The Wall") |
| => The Wall |
| |
| >> db[:dump].call |
| => {"Eagles"=>"Hell Freezes Over", "Pink Floyd"=>"The Wall"} |
| |
| >> db[:delete].call("Pink Floyd") |
| => The Wall |
| |
| >> db[:dump].call |
| => {"Eagles"=>"Hell Freezes Over", "Pink Floyd"=>nil} |
The complement method was previously defined as such:
| def complement(predicate) |
| lambda do |value| |
| not predicate.call(value) |
| end |
| end |
Convert complement into a lambda that returns another lambda. You should then be able to invoke complement like so:
| >> complement.call(is_even).call(4) |
| => false |
| |
| >> complement.call(is_even).call(5) |
| => true |
Usually we think of reduce as combining the elements of a list into a single value. However, you might be surprised to realize that it is more general than that. Here’s a challenge. By only using reduce, take [1, 2, 3, 4, 5] and turn it into [2, 4, 6, 8, 10].