Engee documentation
Notebook

Currying implementation in Julia language

This example demonstrates the implementation of the "currying" algorithm in the Julia programming language, which allows you to convert a function of several arguments into a sequence of functions of one argument.

Introduction

Currying is a functional programming technique in which a function with multiple parameters is transformed into a chain of functions, each of which takes one argument. This is especially useful for creating partially applied functions and improving the modularity and reusability of the code.

The main part

Let's take a closer look at each fragment of the program, its syntax and semantics of operation.

In [ ]:
"""
Defining the `addN` function, which takes a number of type `Number` and returns a new function.
The type of the accepted argument is specified by the annotation `n::Number`
The type of the returned value is specified by the annotation `::Function`
"""
function addN(n::Number)::Function
    # The auxiliary function `adder` is defined inside this function
    # It also accepts a number of type `Number` and returns the sum of its argument.
    # and the values of the variable `n` from the external viewport.
    adder(x::Number) = n + x
    
    # Returning the created `adder` function. Since `n` is stored in the closure,
    # you can use its value even after completing the execution of `addN'.
    return adder
end

Now let's see how you can use this feature in practice.:

In [ ]:
# Let's create a function that will add 5 to any passed number.
addFive = addN(5)

# Now let's call this function with the argument 10:
result = addFive(10)  # result = 15

# Similarly, let's create another function to add 3:
addThree = addN(3)
anotherResult = addThree(7)  # anotherResult = 10

Function addN implements the idea of partial application: instead of adding two numbers at once, we first fix one number (n) and we get a new function that knows that we need to add exactly this number. This concept is widely used in functional programming and allows you to write more flexible and readable code.

Conclusion

We have reviewed the implementation of currying in the Julia language, and created a function addN, which returns a closure that preserves the value of the first argument and can be used repeatedly to add any number with this value. This technique makes it easy to create specialized versions of a common function and effectively use higher-order functions.

The example was developed using materials from Rosetta Code