Functions
Functions in PascalABC.NET
What are Functions?
In programming, a function is a block of organized, reusable code designed to perform a single task. Unlike procedures, functions return a computed value back to the caller. They help break down complex tasks into simpler steps, enhancing clarity and efficiency.
Simple Function Example
Let's start with a basic function that calculates the sum of two numbers:
function AddNumbers(a, b: integer): integer;
begin
Result := a + b;
end;
begin
println(AddNumbers(3, 5)); // Output: 8
end.
This simple function takes two integers, adds them together, and returns their sum.
Function Return Types
Each function must specify the type of value it returns. Common types include integers, floats, strings, etc.
String Function Example
function GetFullName(firstName, lastName: string): string;
begin
Result := firstName + ' ' + lastName;
end;
begin
println(GetFullName('John', 'Doe')); // Output: John Doe
end.
This function concatenates two names into one full name and returns it as a string.
Recursive Functions
Recursion occurs when a function calls itself repeatedly until some condition stops the recursion. Here's an example calculating factorials recursively:
function Factorial(n: integer): integer;
begin
if n <= 1 then
Result := 1
else
Result := n * Factorial(n - 1);
end;
begin
println(Factorial(5)); // Output: 120
end.
This recursive function computes the factorial of a given number by multiplying it successively with decreasing values until reaching 1.
Default Parameters
You can define default parameter values in functions, allowing users to omit certain arguments during invocation:
function Power(base: real; exponent: integer := 2): real;
begin
Result := base ** exponent;
end;
begin
println(Power(3)); // Output: 9 (default exponent is 2)
println(Power(3, 3)); // Output: 27 (explicit exponent provided)
end.
In this case, the power function accepts an optional exponent parameter, defaulted to 2 unless explicitly overridden.
Overloading Functions
PascalABC.NET supports overloading, enabling multiple versions of a function with the same name but differing signatures (parameter types or counts).
function Multiply(a, b: integer): integer;
begin
Result := a * b;
end;
function Multiply(a, b: real): real;
begin
Result := a * b;
end;
begin
println(Multiply(3, 4)); // Calls int version, Output: 12
println(Multiply(3.5, 2.5)); // Calls float version, Output: 8.75
end.
Here, we've defined two versions of the multiply function—one accepting integers and another taking floating-point numbers. The correct variant is chosen based on the provided arguments' types.
Conclusion
Functions allow breaking larger problems into small, modular pieces, promoting cleaner design and reuse across applications. Understanding function definitions, return types, recursion, defaults, and overloading provides essential tools for effective programming in PascalABC.NET.