Created
November 16, 2010 09:01
-
-
Save kirel/701598 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# easy example | |
def multiplier n | |
lambda { |m| n*m } | |
end | |
# advanced examples | |
class Proc | |
def * other | |
lambda { |*args| self.call(*other.call(*args)) } # other is variable form enclosing scope | |
end | |
def ** n | |
lambda { |*args| (n.times.map { self }.inject(:*)).call(*args) } # n is variable form enclosing scope | |
end | |
end | |
require "test/unit" | |
class TestLambdas < Test::Unit::TestCase | |
def test_multiplier | |
times_5 = multiplier(5) | |
assert_equal times_5.call(3), 5 * 3 | |
end | |
def test_composition | |
f = lambda { |x| x**2 } | |
assert_equal (f*f)[3], 3**4 | |
end | |
def test_exp | |
f = lambda { |x| x**2 } | |
assert_equal (f**3)[3], (f*f*f)[3] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment