Audvik Labs

What is Currying in Ruby?


Currying is a technique in which a function accepts N parameters and turns it into a sequence of functions, each of them take 1 parameter.

In mathematics and computer sciencecurrying is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument. For example, a function that takes two arguments, one from X and one from Y, and produces outputs in Z, by currying is translated into a function that takes a single argument from X and produces as outputs functions from Y to Z. Currying is related to, but not the same as, partial application.

Example in Ruby:

power_numbers = -> (x,y) do

In the above example, lambda take two parameters , and return the product of the two.

power = power_numbers.curry.(2)

In the above code we are setting a base number to which we will do an exponential calculation

puts power.(4)    #16

The above code to calculate the value 2**4 and return 16.

Leave a comment

Your email address will not be published. Required fields are marked *