On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Functions That Take Functions
  4. 2. Functions That Return Functions
  5. 3. Passing a Named Function
  6. 4. The Built-In Higher-Order Methods
  7. Code Examples
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 040: Higher-Order Functions

Day14: Lambdas, Higher-Order Functions & Closures
Lecture040 of 057
Estimated video length12 min
TargetDart 3.12
LevelBeginner

where, map and sort don'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, fold and any

1. Functions That Take Functions

Give the parameter a function type:

dart
void repeat(int times, void Function(int) action) {
  for (var i = 1; i <= times; i++) {
    action(i);
  }
}

repeat(3, (i) => print('Round $i'));

Output

code
Round 1
Round 2
Round 3

repeat handles the counting; the lambda decides what happens each round.

dart
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

dart
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.0

multiplier 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:

dart
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

dart
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
MethodYour function…Result
where(f)returns true to keep an itemthe kept items
map(f)turns each item into something newthe new items
reduce(f)combines two values into onea single value
fold(start, f)like reduce, but with a starting valuea single value
any(f) / every(f)tests an itemtrue / false

Code Examples

Example 1: A Product Filter

dart
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

code
Cheap: [Mouse, Kettle, Lamp]
Tech: [Laptop, Mouse]
Total value: Rs 158200.0
Home items: KETTLE, LAMP

filterProducts 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

dart
repeat(2, print('hi'));
code
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

dart
print(applyTwice(3, (String s) => s.length));
code
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

  1. What makes a function "higher-order"?
  2. Write void twiceDo(void Function() action) that calls action two times.
  3. What does applyTwice(5, (n) => n * 2) return?
  4. Using multiplier from Section 2, what is multiplier(3)(4)?
  5. What does [2, 3, 4].reduce((a, b) => a * b) give?

Practice Answers

  1. It takes a function as a parameter, returns a function, or both.
dart
void twiceDo(void Function() action) {
  action();
  action();
}
  1. 20 (5 → 10 → 20).
  2. 12
  3. 24

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, any and every are built-in higher-order methods.