Passing Functions as Arguments
Part of the Logic & Flow section of Coddy's Dart journey — lesson 45 of 65.
In programming, functions can do more than just accept simple values like numbers or strings - they can also accept other functions as parameters. This powerful concept is called a higher-order function, and it opens up entirely new ways to write flexible, reusable code.
When you pass a function as an argument, you're essentially giving another function the ability to decide what operation to perform. Think of it like giving someone a tool and letting them choose how to use it on different materials.
void processNumbers(List<int> numbers, Function operation) {
for (int number in numbers) {
operation(number);
}
}In this example, processNumbers takes a list and a function as parameters. The function parameter operation can be any function that accepts an integer. This means you could pass a function that prints numbers, doubles them, or performs any other operation you need.
This approach makes your code incredibly flexible - instead of writing separate functions for every possible operation, you write one function that can work with many different operations by accepting them as parameters.
Challenge
EasyCreate a program that demonstrates passing functions as arguments by building a flexible number processor. Your program will create different processing functions and pass them to a main processor function that applies the operation to a list of numbers.
- Read a string input containing numbers separated by commas (e.g.,
"1,2,3,4,5") - Read a string input representing the operation type (
"double","square", or"increment") - Split the first input into a list of strings and convert each to an integer
- Create three separate functions:
doubleNumber- takes an integer and returns it multiplied by 2squareNumber- takes an integer and returns it multiplied by itselfincrementNumber- takes an integer and returns it plus 1- Create a main function called
processNumbersthat takes a list of integers and a function as parameters - The
processNumbersfunction should apply the given function to each number in the list and return a new list with the results - Based on the operation type input, pass the appropriate function to
processNumbers - Display the results in the exact format shown below
For example, if the inputs are "2,4,6,8" and "double", your program should output:
Number Processor
================
Original numbers: [2, 4, 6, 8]
Operation: double
Processing numbers...
Result: [4, 8, 12, 16]
Operation completed successfullyIf the inputs are "3,5,7" and "square", your program should output:
Number Processor
================
Original numbers: [3, 5, 7]
Operation: square
Processing numbers...
Result: [9, 25, 49]
Operation completed successfullyIf the inputs are "10,20,30" and "increment", your program should output:
Number Processor
================
Original numbers: [10, 20, 30]
Operation: increment
Processing numbers...
Result: [11, 21, 31]
Operation completed successfullyYour program must demonstrate the concept of higher-order functions by passing one of the three operation functions as an argument to the processNumbers function. Use conditional statements to determine which function to pass based on the operation type input. The processNumbers function should iterate through the input list, apply the given function to each element, and collect the results in a new list.
Cheat sheet
Higher-order functions are functions that can accept other functions as parameters, enabling flexible and reusable code.
To pass a function as an argument, define a parameter of type Function:
void processNumbers(List<int> numbers, Function operation) {
for (int number in numbers) {
operation(number);
}
}This allows you to pass different functions to perform various operations on the same data, making your code more modular and avoiding the need to write separate functions for every possible operation.
Try it yourself
import 'dart:io';
void main() {
// Read input
String? numbersInput = stdin.readLineSync();
String? operation = stdin.readLineSync();
// Convert string input to list of integers
List<int> numbers = numbersInput!.split(',').map((e) => int.parse(e.trim())).toList();
// TODO: Create the three operation functions (doubleNumber, squareNumber, incrementNumber)
// TODO: Create the processNumbers function that takes a list and a function as parameters
// TODO: Use conditional statements to determine which function to pass based on operation type
// TODO: Call processNumbers with the appropriate function and store the result
// Output the results in the required format
print('Number Processor');
print('================');
print('Original numbers: $numbers');
print('Operation: $operation');
print('Processing numbers...');
// TODO: Print the result list here
print('Operation completed successfully');
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced List Manipulation
List Properties: first & lastList State: isEmpty & isNotEmpReversing a ListAdding to a List: insertList Removal: removeWhereFinding in a List: indexOfSorting a ListShuffling a ListRecap - List Organizer4Advanced Map Manipulation
Iterating Over a MapChecking for Keys and ValuesMap Properties: keys & valuesConditional Add: putIfAbsentRemoving Entries from a MapNested MapsRecap - Inventory Update7Advanced Functions
Anonymous FunctionsPassing Functions as ArgumentsUnderstanding ClosuresIntroduction to RecursionRecursive Function: CountdownRecursive Function: FactorialRecap - List Processor2Functional List Operations
Transforming with 'map'Filtering with 'where'Using '.toList()'Checking Conditions with 'any'Conditions with 'every'Finding with 'firstWhere'Recap - Data Filtering5Project: Shopping Cart Calc
Project SetupAdding Items to the Cart3Sets
What is a Set?Creating a SetAdding and Removing from SetsChecking for Elements in a SetConverting a List to a SetSet UnionSet IntersectionSet DifferenceRecap - Unique Guest List