Functions can be viewed in multiple representations. You already know one of them: Contracts, which specify the Name, Domain, and Range of a function. Contracts are a way of thinking of functions as a mapping between one set of data and another. For example, a mapping from Numbers to Strings:

f :: Number -> String

Another way to view functions is with Examples. Examples are essentially input-output tables, showing what the function would do for a specific input:

In our programming language, we focus on the last two columns and write them as code:

  f(1) is 1 + 2
  f(2) is 2 + 2
  f(3) is 3 + 2
  f(4) is 4 + 2

Finally, we write a formal function definition ourselves. The pattern in the Examples becomes abstract (or "general"), replacing the inputs with variables. In the example below, the same definition is written in both math and code:

fx = x + 2

fun f​(​x​): x + 2 end

Look for connections between these three representations!

  • The function name is always the same, whether looking at the Contract, Examples, or Definition.

  • The number of inputs in the Examples is always the same as the number of types in the Domain, which is always the same as the number of variables in the Definition.

  • The "what the function does" pattern in the Examples is almost the same in the Definition, but with specific inputs replaced by variables.

These materials were developed partly through support of the National Science Foundation, (awards 1042210, 1535276, 1648684, and 1738598). CCbadge Bootstrap by the Bootstrap Community is licensed under a Creative Commons 4.0 Unported License. This license does not grant permission to run training or professional development. Offering training or professional development with materials substantially derived from Bootstrap must be approved in writing by a Bootstrap Director. Permissions beyond the scope of this license, such as to run training, may be available by contacting