/ˈfʌŋkʃən/
noun … “Reusable block that maps inputs to outputs.”
Function is a self-contained, named block of code that performs a specific computation or operation, taking zero or more inputs (arguments) and producing zero or more outputs (return values). Functions encapsulate behavior, promote code reuse, and provide abstraction, allowing complex programs to be composed of smaller, understandable units. In programming, they exist in nearly all paradigms, including Object-Oriented Programming and Functional Programming.
Key characteristics of Function include:
- Inputs (parameters): values supplied to customize behavior or computation.
- Outputs (return values): results produced, which may be used by other code.
- Encapsulation: internal logic is hidden from the calling context, preventing side effects unless explicitly designed.
- Purity (in functional contexts): a pure function produces the same output for the same inputs and avoids modifying external state.
- Composability: functions can call other functions, be passed as arguments, or returned as values (higher-order functions).
Workflow example: A program might use a function to calculate the square of a number. This function can be reused wherever squaring is needed without rewriting the logic.
-- Example: simple square function
function square(x) {
return x * x
}
result = square(5)
print("Square of 5: " + str(result))
-- Output: Square of 5: 25Conceptually, a function is like a machine on an assembly line: you feed it materials (inputs), it performs a well-defined process, and it outputs the finished product, consistently and reliably every time.
See Object-Oriented Programming, Functional Programming, Higher-Order Function, Closure.