Skip to content

Instantly share code, notes, and snippets.

@kirel
Created November 16, 2010 09:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirel/701598 to your computer and use it in GitHub Desktop.
Save kirel/701598 to your computer and use it in GitHub Desktop.
# 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