On this page11 sections
Lecture 040: Higher-Order Functions
| Day | 14: Lambdas, Higher-Order Functions & Closures |
| Lecture | 040 of 057 |
| Estimated video length | 12 min |
| Target | Dart 3.12 |
| Level | Beginner |
where,mapandsortdon't know what you want to filter, change or compare, so you hand them a function that decides. A function that takes a function, or returns one, is a higher-order function. Write your own, and one function can do a hundred different jobs.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lecture 039 (lambdas and function types).
Learning Objectives
- Write a function that takes another function as a parameter
- Write a function that returns a function
- Pass named functions and lambdas as arguments
- Use the built-in higher-order methods
where,map,reduce,foldandany
1. Functions That Take Functions
Give the parameter a function type:
void repeat(int times, void Function(int) action) {
for (var i = 1; i <= times; i++) {
action(i);
}
}
repeat(3, (i) => print('Round $i'));Output
Round 1
Round 2
Round 3repeat handles the counting; the lambda decides what happens each round.
int applyTwice(int value, int Function(int) f) => f(f(value));
print(applyTwice(3, (n) => n + 10)); // 23 (3 → 13 → 23)
print(applyTwice(2, (n) => n * n)); // 16 (2 → 4 → 16)2. Functions That Return Functions
int Function(int) multiplier(int factor) {
return (int n) => n * factor;
}
var twice = multiplier(2);
var times10 = multiplier(10);
print(twice(7)); // 14
print(times10(7)); // 70
double Function(double) discount(double percent) => (price) => price * (1 - percent / 100);
var sale = discount(20);
print(sale(1000)); // 800.0multiplier is a function factory: each call builds a new function with its own factor.
(How the returned function remembers factor is the topic of Lecture 041.)
3. Passing a Named Function
You don't always need a lambda. Pass an existing function by its name, without brackets:
int square(int n) => n * n;
var nums = [1, 2, 3, 4, 5, 6];
print(nums.map(square).toList()); // [1, 4, 9, 16, 25, 36]4. The Built-In Higher-Order Methods
var nums = [1, 2, 3, 4, 5, 6];
print(nums.where((n) => n.isEven).toList()); // [2, 4, 6]
print(nums.map((n) => n * n).toList()); // [1, 4, 9, 16, 25, 36]
print(nums.reduce((a, b) => a + b)); // 21
print(nums.fold<int>(100, (sum, n) => sum + n)); // 121
print(nums.any((n) => n > 5)); // true| Method | Your function… | Result |
|---|---|---|
where(f) | returns true to keep an item | the kept items |
map(f) | turns each item into something new | the new items |
reduce(f) | combines two values into one | a single value |
fold(start, f) | like reduce, but with a starting value | a single value |
any(f) / every(f) | tests an item | true / false |
Code Examples
Example 1: A Product Filter
class Product {
final String name;
final double price;
final String category;
Product(this.name, this.price, this.category);
}
List<Product> filterProducts(List<Product> items, bool Function(Product) test) {
var result = <Product>[];
for (var p in items) {
if (test(p)) result.add(p);
}
return result;
}
void main() {
var products = [
Product('Laptop', 150000, 'tech'),
Product('Mouse', 1500, 'tech'),
Product('Kettle', 4500, 'home'),
Product('Lamp', 2200, 'home'),
];
var cheap = filterProducts(products, (p) => p.price < 5000);
var tech = filterProducts(products, (p) => p.category == 'tech');
print('Cheap: ${cheap.map((p) => p.name).toList()}');
print('Tech: ${tech.map((p) => p.name).toList()}');
var total = products.map((p) => p.price).reduce((a, b) => a + b);
print('Total value: Rs $total');
var names = products.where((p) => p.category == 'home').map((p) => p.name.toUpperCase()).join(', ');
print('Home items: $names');
}Output
Cheap: [Mouse, Kettle, Lamp]
Tech: [Laptop, Mouse]
Total value: Rs 158200.0
Home items: KETTLE, LAMPfilterProducts is written once, and the rule is passed in, so any filter works without a new
function. (It's your own version of where.)
Common Beginner Mistakes
1. Calling the function instead of passing it
repeat(2, print('hi'));Error: This expression has type 'void' and can't be used.print('hi') runs immediately and gives nothing back. Pass a function: repeat(2, (i) => print('hi'));.
2. A function with the wrong shape
print(applyTwice(3, (String s) => s.length));Error: The argument type 'int Function(String)' can't be assigned to the parameter type 'int Function(int)'.The lambda must match the parameter's function type.
3. Adding brackets to a function name: nums.map(square()) calls square with no argument.
Pass square itself: nums.map(square).
Practice Questions
- What makes a function "higher-order"?
- Write
void twiceDo(void Function() action)that callsactiontwo times. - What does
applyTwice(5, (n) => n * 2)return? - Using
multiplierfrom Section 2, what ismultiplier(3)(4)? - What does
[2, 3, 4].reduce((a, b) => a * b)give?
Practice Answers
- It takes a function as a parameter, returns a function, or both.
void twiceDo(void Function() action) {
action();
action();
}20(5 → 10 → 20).1224
Key Takeaways
- A higher-order function takes and/or returns a function.
- Function parameters are typed like
bool Function(Product). - Pass a lambda, or a named function without brackets.
- Returning a function builds custom functions on demand (
multiplier(2)). where,map,reduce,fold,anyandeveryare built-in higher-order methods.