4.12.1.1–4.12.1.3 - Function types, first-class values and application (VB.NET)
Learn how a function maps inputs to outputs, how a function itself can be a value, and how application supplies its arguments.
The VB.NET route is incomplete: runnable support pending. The native examples and code questions here are written-only. This topic is examined in Paper 2.
Domain, co-domain and function types
A function assigns exactly one output to each permitted input. Its type records the sets from which those inputs and outputs are drawn.
Domain and co-domain
The domain, , is the set of permitted inputs. The co-domain, , is the set in which every output must lie. Both are subsets of values in some data type.
For example, let , , and . This defines . All five permitted inputs have one output, but the outputs actually reached are only . This reached set is the range. The unused values 2 and 3 can still belong to the co-domain. Different inputs may have the same output: both −2 and 2 map to 4.
A second example maps a lowercase letter to its alphabetical position: , with and . Here every co-domain value is reached. That is possible, but it is not required of every function.
The declaration Func(Of Integer, Integer) describes a VB.NET function value taking an Integer and returning an Integer. It describes data types, not a narrower permitted set such as . A task must state any input restriction separately. Mathematical integers are unbounded; VB.NET Integer values are bounded. Our small examples stay within their range.
First-class function values
A first-class value can appear in expressions, be assigned to a variable, be passed as an argument, and be returned from a function. Integers and strings commonly have these capabilities; functions have them too in functional languages and in languages such as VB.NET that support function values.
A VB.NET delegate is a value referring to callable code. Func(Of Integer, Integer) is a delegate type whose final type parameter is the result type. A lambda expression creates an unnamed function: Function(n As Integer) n * 2 returns twice its argument. A single-line lambda contains its result expression without Return or End Function.
Imports System
Module Program
Function ChooseTransform() As Func(Of Integer, Integer)
Return Function(n As Integer) n * 2
End Function
Function ApplyTwice(transform As Func(Of Integer, Integer),
value As Integer) As Integer
Return transform(transform(value))
End Function
Sub Main()
Dim doubleValue As Func(Of Integer, Integer) = ChooseTransform()
Dim anotherName As Func(Of Integer, Integer) = doubleValue
Console.WriteLine(ApplyTwice(anotherName, 3))
End Sub
End Module
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account