4.12.1.1–4.12.1.3 - Function types, first-class values and application (C#)
Learn how function types describe permitted inputs and results, how a function can be stored and passed as a value, and how application supplies its arguments.
C# route status: incomplete: runnable support pending. The code questions use written practice.
Domain, co-domain and function types
A function assigns exactly one result to each permitted input, and its type describes the sets those inputs and results belong to.
Function type
The notation says that accepts an argument from and produces a result in . is the domain and is the co-domain.
Both sets are subsets of objects in a data type. A domain might be all integers, a limited set of integers or the lower-case characters. A co-domain states the permitted results; the range is the set of results the function actually produces. The range can be smaller than the co-domain.
For example, let , and . Then , but its range is only . Every input has a result in ; it is unnecessary to produce 0, 2 or every other member of . Several inputs may share a result: . That still defines a function.
The alphabet mapping , where , and so on, does use every co-domain member. The rule and chosen domain decide the range.
C# represents a function value with a delegate type such as Func<char, int>. The final type parameter is the result type; earlier parameters are argument types. A programmer must still state a narrower permitted input set when the C# type alone does not express it.
using System;
class Program
{
static void Main()
{
// Domain: lower-case letters a to z only.
Func<char, int> position = letter => letter - 'a';
Console.WriteLine(position('d')); // 3
}
}
char permits many characters, but this mapping's stated domain does not. Calling it with 'A' violates the contract; the declared C# type is not evidence that every character is a valid alphabet input. Similarly, machine int has a finite range, so this implementation is not a function over unlimited mathematical integers.
First-class function values
A first-class function can be manipulated as a value instead of only being called by a fixed name.
First-class value
A value that can appear in expressions, be assigned to a variable, be passed as an argument and be returned from a function call. A function is first-class when these operations apply to the function itself.
Passing doubleValue passes the function; passing doubleValue(5) first applies it and passes the result 10. The distinction matters because a receiving function can choose when and to which value it applies the supplied operation.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account