diff --git a/curriculum/challenges/english/blocks/lecture-understanding-functional-programming/6734061fe116df617a564a37.md b/curriculum/challenges/english/blocks/lecture-understanding-functional-programming/6734061fe116df617a564a37.md index 2b0b8ee08a6..54c11d010ee 100644 --- a/curriculum/challenges/english/blocks/lecture-understanding-functional-programming/6734061fe116df617a564a37.md +++ b/curriculum/challenges/english/blocks/lecture-understanding-functional-programming/6734061fe116df617a564a37.md @@ -5,22 +5,28 @@ challengeType: 19 dashedName: what-is-currying-and-how-does-it-work --- -# --description-- +# --interactive-- Currying is a technique where we transform a function that takes multiple arguments into a sequence of functions, each taking a single argument. Let's start with a basic example. Imagine we have a function that adds two numbers: +:::interactive_editor + ```js function add(a, b) { return a + b; } -console.log(add(3, 4)); // Output: 7 +console.log(add(3, 4)); // 7 ``` +::: + This is a function that takes two arguments and returns their sum. Now, let's see how we can curry this function: +:::interactive_editor + ```js function curriedAdd(a) { return function(b) { @@ -28,21 +34,33 @@ function curriedAdd(a) { } } -console.log(curriedAdd(3)(4)); // Output: 7 +console.log(curriedAdd(3)(4)); // 7 ``` +::: + In this curry converted code, instead of taking two arguments at once, we have a function that takes the first argument and returns another function. This returned function then takes the second argument and performs the addition. We call it like `curriedAdd(3)(4)`, where each pair of parentheses represents a function call. But why would we want to do this? Currying allows us to create some special functions easily. For example, we could create a function that always adds five to any number: +:::interactive_editor + ```js +function curriedAdd(a) { + return function(b) { + return a + b; + } +} + const addFive = curriedAdd(5); -console.log(addFive(10)); // Output: 15 -console.log(addFive(20)); // Output: 25 +console.log(addFive(10)); // 15 +console.log(addFive(20)); // 25 ``` +::: + Here, `addFive` is a function that's always ready to add five to whatever number we give it. This is a simple example of partial application, where we fix a certain number of arguments to a function, producing another function that takes fewer arguments. While our examples have focused on functions with two arguments, currying can be applied to functions with any number of arguments.