Chapter 3: Functions - Code Reusability and Organization
Functions are the fundamental building blocks for organizing logic. A function is a named chunk of code that you can call multiple times.
Defining a Function
Use the def keyword, followed by the function name, parameters with their types, and a return type.
def calculate_energy(mass: float, speed: float) -> float:
return 0.5 * mass * (speed * speed)
val kinetic_energy: float = calculate_energy(100.0, 30.0)
print(f"Energy: {kinetic_energy} Joules")
Void Functions
If a function doesn't return a value, use -> void.
def log_message(message: string) -> void:
print(f"[LOG]: {message}")
log_message("System initialized.")
Multiple Parameters and Return Values
Functions can accept multiple parameters and return a single value of any type.
def divide(a: float, b: float) -> float:
if b == 0.0:
print("Error: Division by zero!")
return 0.0
return a / b
val result: float = divide(10.0, 2.0)
Chapter 4: Data Structures - Managing Collections
Variables are great, but you often need to manage a collection of related data. REDLINE provides two primary structures: lists and dictionaries.
Lists
A list is an ordered, indexed collection of elements of a single type. Think of it as a dynamic array.
val temperatures: list[float] = [23.5, 24.1, 22.9, 25.0]
val first_temp: float = temperatures[0] # Index access (0-based)
# Adding elements
var log: list[string] = []
append(log, "System start")
append(log, "All systems nominal")
print(f"Log entries: {len(log)}")
Dictionaries
A dict (dictionary) is a key-value store. Unlike lists, which are accessed by numeric indices, dictionaries use keys of any type.
val crew_roles: dict[string, string] = {
"Alice": "Captain",
"Bob": "Engineer",
"Charlie": "Pilot"
}
val alice_role: string = crew_roles["Alice"]
print(f"Alice is the {alice_role}")
Built-In Functions for Collections
len(collection): Returns the size of a list or dictionary.append(list, value): Adds an element to the end of a list.sort(list): Sorts a list in ascending order (in-place).reverse(list): Reverses a list in-place.find(list, value): Returns the index of a value in a list, or-1if not found.