Skip to content

Instantly share code, notes, and snippets.

@parsonsmatt
Created July 23, 2015 22:25
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 parsonsmatt/8acd90d303fb84742826 to your computer and use it in GitHub Desktop.
Save parsonsmatt/8acd90d303fb84742826 to your computer and use it in GitHub Desktop.
when currying is useful
# Currying: What, How, Why
# Currying is a way to change the arity of functions.
add = -> x, y { x + y }
# Any function that takes multiple arguments can be expressed as a function
# that takes a single argument, and returns a function taking a single
# argument, etc. until eventually all arguments are given and a value is
# returned.
add = -> x { -> y { x + y } }
add3 = add[3]
=> Proc
add3[5]
=> 8
# So the what and how are pretty easy, but many people are still left wondering
# "why would anyone care about that? it is totally useless"
# And frankly most explanations on *why* it is cool are not that great, unless
# you already know/like it.
# It's just the adapter pattern for functions.
[1, 2, 3].map do |x|
x + 3
end
=> [4, 5, 6]
# Ruby's map, filter, reduce, etc. take a very convenient & syntax for messages.
[1, 2, 3].filter(&:even?)
=> [2]
# YEAH THAT'S SO CONCISE! You can also pass lambdas to these:
even = -> x { x % 2 == 0 }
[1, 2, 3].filter(&even)
=> [2]
# But what if we want to add a number to each element in an array?
[1,2,3].map(&:+, 3) # bzzrt doesn't work
[1,2,3].map { |x| x + 3 } # ugh but that's so many characters
plus = -> x, y { x + y }
[1,2,3].map(&plus) # But I just want it to add 3! THis isn't right..
# Currying to the rescue!
plus = -> x { -> y { x + y } }
[1, 2, 3].map(&plus[3])
=> [4, 5, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment