0
0
Rubyprogramming~5 mins

Curry and partial application in Ruby

Choose your learning style9 modes available
Introduction

Curry and partial application help you reuse functions by fixing some inputs early. This makes your code simpler and easier to understand.

When you want to create a new function by fixing some arguments of an existing function.
When you have a function that takes many inputs, but you often use it with some inputs the same.
When you want to break down complex tasks into smaller, reusable steps.
When you want to delay providing some inputs until later in your program.
When you want to write cleaner and more readable code by reusing functions.
Syntax
Ruby
curried_function = original_function.curry
partial_function = curried_function.call(fixed_arg1).call(fixed_arg2)

Use .curry on a Proc or lambda to enable currying.

Calling the curried function with fewer arguments returns a new function waiting for the rest.

Examples
This example creates a curried add function, then fixes the first number to 5, making a new function that adds 5 to any number.
Ruby
add = ->(a, b) { a + b }
curried_add = add.curry
add_five = curried_add.call(5)
puts add_five.call(3)  # Output: 8
Here, we fix the first two numbers (2 and 3) and get a new function that multiplies the result by the last number.
Ruby
multiply = ->(x, y, z) { x * y * z }
curried_multiply = multiply.curry
partial = curried_multiply.call(2).call(3)
puts partial.call(4)  # Output: 24
Sample Program

This program creates a greeting function, then fixes the greeting to "Hello". It then greets different people using the new function.

Ruby
greet = ->(greeting, name) { "#{greeting}, #{name}!" }
curried_greet = greet.curry
say_hello = curried_greet.call("Hello")
puts say_hello.call("Alice")
puts say_hello.call("Bob")
OutputSuccess
Important Notes

Currying works only on Procs or lambdas, not on regular methods directly.

Partial application is a practical use of currying where you fix some arguments early.

Currying helps make your code more modular and reusable.

Summary

Curry transforms a function so you can call it with fewer arguments and get a new function.

Partial application means fixing some arguments of a function to create a simpler function.

Ruby's .curry method makes currying easy with lambdas and Procs.