4.12.1.4–4.12.1.5 - Partial application and function composition (VB.NET)
Learn how supplying some arguments produces a specialised function, and how composition connects one function's output to another's input.
The VB.NET route is incomplete: runnable support pending. All native code tasks in this Paper 2 topic are written-only.
One-, two- and three-argument types
A function can receive its inputs together, or one at a time through a chain of returned functions. Currying represents a multi-argument function in the second way.
An ordinary two-input addition mapping has type . In the curried view, addition has type
.
The first integer selects a function; the second integer is supplied to that function to obtain the result. Arrows associate to the right, so means the same type with the brackets omitted. Application associates to the left: means , giving 10. Spaces here are functional application notation, not VB.NET syntax.
| Function | Curried type | Application and remaining type |
|---|---|---|
| is the integer 10; no input remains | ||
| has type | ||
| has two arrows left; has one |
Applying the sole argument to a one-argument function whose result is an integer completes it. Applying one or two arguments to the three-input example leaves a function; applying all three gives a value. Do not confuse partial application, which deliberately leaves arguments to supply later, with a function being undefined for some input.
Partial application and returned functions
Partial application fixes some of a function's arguments and returns a function awaiting the rest. It is useful when the fixed input will be reused: a general addition function can become an add-five function without repeating the fixed argument at every use.
Imports System
Module Program
Function CurriedAdd(a As Integer) As Func(Of Integer, Integer)
Return Function(b As Integer) a + b
End Function
Function CurriedTotal(a As Integer) As Func(Of Integer, Func(Of Integer, Integer))
Return Function(b As Integer) As Func(Of Integer, Integer)
Return Function(c As Integer) a + b + c
End Function
End Function
Sub Main()
Dim addFive As Func(Of Integer, Integer) = CurriedAdd(5)
Console.WriteLine(addFive(8))
Dim afterTwo As Func(Of Integer, Func(Of Integer, Integer)) = CurriedTotal(2)
Dim afterTwoAndFive As Func(Of Integer, Integer) = afterTwo(5)
Console.WriteLine(afterTwoAndFive(7))
End Sub
End Module
The outputs are 13 and 14. CurriedAdd(5) returns a delegate; its body has not yet added a second input. The returned lambda retains access to a. This association between a function and its retained surrounding variables is a closure. We leave the fixed values unchanged, so later applications reuse the same values.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account