Skip to content

Instantly share code, notes, and snippets.

@srawlins
Created February 22, 2014 00:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srawlins/9146528 to your computer and use it in GitHub Desktop.
Save srawlins/9146528 to your computer and use it in GitHub Desktop.
flexible curry for Procs and methods in Ruby
def curry(prc, *args)
Proc.new { |*remaining| prc.call(*args.map { |arg| arg || remaining.shift }) }
end
def curry_m(m, n, *args)
define_method(m, curry(method(n), *args))
end
power = ->(a,b){ "#{a}**#{b} is #{a**b}" }
square = curry power, nil, 2
pow2 = curry power, 2, nil
puts "3 squared is #{square.call(3)}" #=> 3 squared is 3**2 is 9
puts "two to the 3 is #{pow2.call(3)}" #=> two to the 3 is 2**3 is 8
list = ->(a,b,c,d) { "#{a}, #{b}, #{c}, #{d}" }
static_a = curry list, :hi, nil, nil, nil
static_b_c = curry list, nil, :sam, :adam, nil
puts "static_a: #{static_a.call(:b, :c, :d)}" #=> static_a: hi, b, c, d
puts "static_b_c: #{static_b_c.call(:a, :d)}" #=> static_b_c: a, sam, adam, d
def power_m(a,b); a**b; end
curry_m(:square_m, :power_m, nil, 2)
curry_m(:pow2_m, :power_m, 2, nil)
puts "3 squared is #{square_m(3)}" #=> 3 squared is 9
puts "two to the 3 is #{pow2_m(3)}" #=> two to the 3 is 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment