Search⌘ K
AI Features

Use Currying for Function Chaining

Explore how currying converts functions with multiple arguments into nested single-argument functions in OCaml. Understand partial application to create new functions by fixing some arguments, enabling flexible and reusable function chaining. This lesson helps you grasp key functional programming concepts that differ from imperative approaches.

Function with multiple arguments

One significant insight from lambda calculus is currying—we can formulate a function accepting multiple arguments as a nested chain of single-valued functions. Most functional programming languages, including OCaml, incorporate this technique into the language.

To illustrate, let’s look at OCaml’s built-in binary operator, +, to add two integers. Internally, OCaml implements + as a normal function. Although we normally use + in the infix notation like 1 + 2, OCaml allows us to use + in the prefix notation by placing it in parentheses (+). This means we can write (+) 1 2.

OCaml
(** Using + in the prefix notation *)
let _ = print_int ((+) 1 2)

Except for its odd name, (+) is a normal function like any other function. It’s a binary function that accepts two integers and returns their sum. Its type is int -> int -> int.

Note: The -> operator is right-associative and so the type is ...