Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Certified Racket AI Expert ยท Lesson 4 of 8

Module Three

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
4
Module 3 ยท Racket AI Specialist โ€“ Repetition & Loops

๐Ÿ”„ Module Three ยท Repetition & Loops โ€“ Making Computers Work Hard

Certified Racket AI Specialist ยท Power of Doing Things Again and Again

๐Ÿ“– Module Introduction

Hello, clever coder! ๐Ÿ‘‹ In Module Two, we taught our computer to make decisions. Now we will teach it something even more powerful: how to repeat tasks.

Think about a mother hen counting her chicks. She doesn't just count once โ€” she counts each chick, one by one. If she had to count 100 chicks, she would do the same action 100 times. Computers are great at this! They never get bored or tired.

In this module, we will learn loops (ways to repeat code) and recursion (a function that calls itself). We'll build programs that can handle big lists, draw patterns, and solve problems that need many steps. By the end, you'll be able to make your computer do the hard work for you โ€” just like a real AI!

โšก Fun fact: Computers can repeat a task millions of times in less than a second. That's why they are so powerful!

๐ŸŽฏ Learning Objectives

After this module, you will be able to:

  • โœ”๏ธ Understand why repetition is important in programming.
  • โœ”๏ธ Use recursion to repeat a task.
  • โœ”๏ธ Write a recursive function that counts down.
  • โœ”๏ธ Use map to apply a function to every item in a list.
  • โœ”๏ธ Use filter to select items from a list.
  • โœ”๏ธ Use foldl (or reduce) to combine items.
  • โœ”๏ธ Build programs that process large amounts of data.
  • โœ”๏ธ Understand when to stop a loop (base case).

๐Ÿ“š Warm-up Story ยท The Endless Dance

Imagine you are at a party, and the DJ plays a song. Everyone starts dancing. When the song ends, the DJ plays the same song again โ€” and again โ€” and again. People keep dancing until the DJ stops.

That's like a loop in programming. The computer does the same action over and over until we tell it to stop.

But there is another way: imagine a line of people. You ask the first person, "What's your name?" They tell you. Then you ask the second person, and so on, until you reach the end of the line. In Racket, we use recursion to do this โ€” a function that keeps calling itself until it reaches the end.

Let's learn both ways, starting with recursion โ€” the Racket way!

   Loop (repeat)
   +--------+
   | Do work |
   +--------+
       |
       V
   +--------+
   | Repeat? |
   +--------+
       |
    Yes/No
  

๐Ÿงฉ Main Lessons

Lesson 1 ยท Why Repeat? The Power of Doing Things Many Times

Definition: Repetition means doing the same thing more than once.

Why important: Many tasks in AI involve doing the same thing to a lot of data โ€” like checking all the numbers in a list, or training a model by repeating steps.

Simple explanation: If you want to eat 10 candies, you pick one, eat it, pick one, eat it... you repeat the "pick and eat" action 10 times.

Real-life example: A teacher checking homework for 30 students โ€” checks each student's work one by one.

School example: Writing your name 5 times to practice.

Home example: Taking out all the dishes from a dishwasher โ€” one plate at a time.

Nigerian example: Counting the number of mangoes in a basket โ€” pick one, count, pick one, count.

Illustration:

   Task: Count apples
   Step 1: take one apple, count 1
   Step 2: take one apple, count 2
   Step 3: take one apple, count 3
   ... repeat until no apples left
  
๐Ÿ“Œ Mini summary: Repetition lets computers handle big tasks by breaking them into small, repeated steps.

Lesson 2 ยท Recursion โ€“ A Function That Calls Itself

Definition: Recursion is when a function calls itself to solve a smaller version of the same problem.

Why important: Recursion is the main way to repeat things in Racket. It's elegant and powerful.

Simple explanation: Imagine you are in a maze. You look around. If you see the exit, you go out. If not, you take one step and then solve the maze again. That's recursion โ€” solving a smaller version of the same problem.

Real-life: Looking for a book in a stack: you check the top, if it's not there, you check the next, and so on.

School: Counting down to zero: "5, 4, 3, 2, 1, blast off!" Each step is a smaller count.

Home: Unwrapping a gift: you open one layer, if there's another layer, you open that too.

Nigerian: Sharing oranges: give one to a friend, then share the rest.

Illustration:

   (define (count-down n)
     (if (<= n 0)
         "blast off!"
         (begin
           (display n)
           (count-down (- n 1)))))
   (count-down 5)
   โ†’ 5 4 3 2 1 blast off!
  
๐Ÿ“Œ Mini summary: Recursion is a function that calls itself. It needs a stop condition (base case).

Lesson 3 ยท The Base Case โ€“ When to Stop

Definition: The base case is the condition that stops the recursion. Without it, the function would run forever.

Why important: Every recursive function must have a base case to avoid infinite loops.

Simple explanation: It's like a "STOP" sign. When you reach the base case, you don't continue.

Real-life: In a race, the finish line is the base case โ€” when you cross it, you stop.

School: When you finish a test, you stop writing.

Home: When the pot is empty, you stop serving food.

Nigerian: When the market closes, you stop buying.

Illustration:

   (define (sum-up-to n)
     (if (= n 0)          ; base case
         0                ; stop
         (+ n (sum-up-to (- n 1)))))
   (sum-up-to 5) โ†’ 15   (5+4+3+2+1+0)
  
๐Ÿ“Œ Mini summary: Base case is the safety net that stops recursion.

Lesson 4 ยท Recursion on Lists โ€“ Processing Every Item

Definition: We can use recursion to go through each item in a list and do something with it.

Why important: AI often works with lists of data โ€” like scores, names, or sensor readings.

Simple explanation: Imagine a line of students. You ask the first student a question, then move to the next, until you reach the end.

Real-life: Checking a shopping list: look at first item, buy it, then go to the next.

School: Taking attendance: call each name in the list.

Home: Reading a list of chores: do chore 1, then chore 2, etc.

Nigerian: Going through a list of market items: buy yam, then pepper, then onions.

Illustration:

   (define (sum-list lst)
     (if (empty? lst)      ; base case: empty list
         0
         (+ (first lst) (sum-list (rest lst)))))
   (sum-list '(1 2 3 4)) โ†’ 10
  
๐Ÿ“Œ Mini summary: Recursion can process lists by taking the first item and repeating on the rest.

Lesson 5 ยท Map โ€“ Do Something to Every Item

Definition: map takes a function and a list, and applies that function to every item in the list, returning a new list.

Why important: It's a fast way to transform all items without writing a loop.

Simple explanation: It's like a teacher giving a sticker to every student in the class โ€” one function applied to everyone.

Real-life: Adding tax to every item in a shopping cart.

School: Adding 5 points to everyone's test score.

Home: Cutting every fruit into pieces.

Nigerian: Adding 10% discount to every item in a price list.

Illustration:

   (define (double x) (* x 2))
   (map double '(1 2 3 4)) โ†’ '(2 4 6 8)
  
๐Ÿ“Œ Mini summary: map applies a function to every item in a list.

Lesson 6 ยท Filter โ€“ Keep Only What We Want

Definition: filter takes a test function and a list, and returns a new list with only the items that pass the test.

Why important: AI often needs to pick out certain data โ€” like finding all numbers greater than 50.

Simple explanation: It's like a sieve โ€” you shake it and only small particles pass through. Filter keeps only the items that are true.

Real-life: Sorting out ripe fruits from unripe ones.

School: Picking all students who scored above 70.

Home: Selecting only your favorite toys.

Nigerian: Choosing only the big fish from a basket.

Illustration:

   (define (even? n) (= 0 (remainder n 2)))
   (filter even? '(1 2 3 4 5)) โ†’ '(2 4)
  
๐Ÿ“Œ Mini summary: filter selects items that satisfy a condition.

Lesson 7 ยท Fold (Reduce) โ€“ Combine Everything

Definition: foldl (or fold) takes a function, an initial value, and a list, and combines all items into one value.

Why important: It's used for summing, multiplying, or combining data in many AI tasks.

Simple explanation: Think of a big pile of numbers. You start with 0, then add each number one by one to get the total.

Real-life: Adding up all the prices in a shopping cart.

School: Calculating the total marks for all subjects.

Home: Counting how many toys you have by adding 1 each time.

Nigerian: Summing the cost of all items in a market list.

Illustration:

   (foldl + 0 '(1 2 3 4)) โ†’ 10
   (foldl * 1 '(1 2 3 4)) โ†’ 24
  
๐Ÿ“Œ Mini summary: fold combines all items in a list into a single result.

Lesson 8 ยท Building a Recursive Function โ€“ Step by Step

Let's build a function that counts the number of items in a list (without using length).

   (define (my-length lst)
     (if (empty? lst)
         0
         (+ 1 (my-length (rest lst)))))
   (my-length '(a b c d)) โ†’ 4
  

Steps: 1) If list is empty, return 0. 2) Otherwise, count 1 for the first item, and add the length of the rest.

๐Ÿ“Œ Mini summary: Recursion breaks the problem into a small step + the same problem on a smaller input.

Lesson 9 ยท The Power of Recursion โ€“ Factorial

Factorial is a famous recursion example. 5! = 5 ร— 4 ร— 3 ร— 2 ร— 1.

   (define (factorial n)
     (if (= n 0)
         1
         (* n (factorial (- n 1)))))
   (factorial 5) โ†’ 120
  

AI uses factorial in probability and statistics.

๐Ÿ“Œ Mini summary: Factorial shows how recursion breaks a big problem into smaller ones.

Lesson 10 ยท Recursion vs. Loops in Other Languages

In Racket, we use recursion instead of traditional loops (like 'for' or 'while' in other languages). Recursion is more functional and elegant.

LanguageLoop style
Pythonfor i in range(5): print(i)
Racket(define (loop n) (if (> n 0) (begin (display n) (loop (- n 1))) 'done))
๐Ÿ“Œ Mini summary: Racket uses recursion where other languages use loops.

Lesson 11 ยท Processing Big Data โ€“ AI in Action

AI systems process huge lists of data. We can use map, filter, and fold to clean and analyze data. For example, we can filter out low scores, map each score to a grade, and fold to get the average.

๐Ÿ“Œ Mini summary: These list functions are the building blocks of AI data processing.

Lesson 12 ยท Putting It All Together โ€“ A Data Analyzer

Let's build a program that takes a list of numbers, keeps only the even ones, doubles them, and sums them up.

   (define (process nums)
     (foldl + 0 (map double (filter even? nums))))
   (process '(1 2 3 4 5 6)) โ†’ 2*2 + 4*2 + 6*2 = 4+8+12 = 24
  

You just built a tiny data pipeline โ€” the same idea used in big AI systems!

๐Ÿ“Œ Mini summary: We combined filter, map, and fold to build a powerful data processor.

๐Ÿ“– Key Vocabulary

  • Recursion: A function that calls itself.
  • Base case: The condition that stops recursion.
  • Map: Apply a function to every item in a list.
  • Filter: Keep items that pass a test.
  • Fold (reduce): Combine all items into one.
  • List processing: Working with lists of data.
  • Data pipeline: A series of transformations on data.

๐Ÿง  Important Concepts

  • Recursion replaces loops: In Racket, we use recursion for repetition.
  • Higher-order functions: map, filter, fold are functions that take other functions.
  • Immutability: We don't change lists; we create new ones.
  • Composition: We combine simple functions to build complex ones.

๐Ÿ“˜ Step-by-Step Explanations

How to write a recursive function:

  1. Identify the base case (smallest problem).
  2. Write what to do for the base case.
  3. Identify the recursive case (how to break the problem down).
  4. Write the recursive call with a smaller input.
  5. Combine the result.

๐ŸŒ Real-life Examples

  • Search engines: filter pages by keywords.
  • Weather apps: process sensor data with map.
  • Online shopping: calculate total price using fold.

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Market data: filter items under 500 Naira.
  • School results: map scores to grades.
  • Traffic data: sum vehicles per hour using fold.

๐ŸŽˆ Fun Examples

  • Count how many cookies you have.
  • Double all the numbers in a list.
  • Keep only your favorite colors from a list.

๐Ÿ  Everyday Examples

  • Making tea: repeat "pour water" until cup is full.
  • Reading a book: read page 1, then page 2, etc.
  • Cleaning: do one chore, then the next.

๐Ÿง‘โ€๐Ÿซ Teacher Notes

Use physical demonstrations: pass a ball around a circle to show recursion. Use boxes to represent lists. Emphasize that recursion is just a function calling itself. Always write the base case first.

๐Ÿ‘ช Parent Tips

Encourage your child to think about patterns of repetition in daily life. Ask: "How would you tell a robot to count all your toys?" This builds the concept of iteration. Practice writing small recursive functions together.

๐ŸŒŸ Interesting Facts

  • The factorial function was invented by Christian Kramp in 1808.
  • Recursion is used in sorting algorithms that power search engines.
  • AI systems use map/filter/fold to prepare data for training.

๐Ÿค” Did You Know?

Racket's map can work with multiple lists at the same time! For example: (map + '(1 2) '(3 4)) โ†’ '(4 6).

๐Ÿงพ Remember This

  • Recursion needs a base case to stop.
  • Map transforms every item.
  • Filter selects some items.
  • Fold combines all items.
  • These functions are the heart of list processing in AI.

โš ๏ธ Common Mistakes

  • Forgetting the base case โ€” causes infinite recursion.
  • Not using rest to shrink the list.
  • Confusing map and filter โ€” map returns same length, filter returns shorter.
  • Using foldl with wrong initial value.

โœ… Best Practices

  • Always write the base case first.
  • Use meaningful names for helper functions.
  • Test with small inputs before big ones.
  • Combine map, filter, fold for clean data processing.

๐Ÿ“Š ASCII Illustrations

   Recursive process:
   function(5)
      |
      V
   function(4)
      |
      V
   function(3)
      |
      V
   function(2)
      |
      V
   function(1)
      |
      V
   function(0) โ†’ base case, returns
  
   Map process:
   [1,2,3] -- map double --> [2,4,6]
  

๐Ÿ“‹ Comparison Table

FunctionWhat it doesReturns
maptransforms each itemlist of same length
filterkeeps items that pass testshorter list
foldlcombines all itemssingle value

๐Ÿ“Œ End-of-Module Summary

You've mastered repetition in Racket! You learned recursion, map, filter, and fold. You can now process lists of any size. These skills are essential for AI โ€” from cleaning data to training models. You are building a powerful toolkit.

โ“ Frequently Asked Questions (10)

  1. What is recursion? โ€” A function that calls itself.
  2. Why do we need a base case? โ€” To stop the recursion.
  3. What does map do? โ€” Applies a function to every item.
  4. What does filter do? โ€” Keeps items that match a condition.
  5. What does fold do? โ€” Combines all items into one.
  6. Can map change the length of a list? โ€” No, it keeps the same length.
  7. Can filter increase the length? โ€” No, it only keeps some.
  8. What is a data pipeline? โ€” A series of transformations like filter, map, fold.
  9. Is recursion faster than loops? โ€” In Racket, recursion is efficient and encouraged.
  10. Can we use recursion with strings? โ€” Yes, by converting strings to lists.

๐Ÿ“ Review Questions (15)

  1. What is recursion?
  2. What is a base case?
  3. Write a recursive function that prints numbers from N to 1.
  4. What does map do?
  5. What does filter do?
  6. What does foldl do?
  7. Write a function that doubles every number in a list using map.
  8. Write a function that keeps only numbers greater than 5 using filter.
  9. Write a function that sums a list using foldl.
  10. What happens if you forget the base case?
  11. Why is recursion useful for lists?
  12. What is a higher-order function?
  13. Can you use map with multiple lists?
  14. Write a recursive function to find the length of a list.
  15. What is the difference between map and filter?

โœ๏ธ Fill-in-the-Blank

  1. ______ is a function that calls itself.
  2. ______ stops recursion.
  3. ______ applies a function to every item in a list.
  4. ______ keeps only the items that satisfy a condition.
  5. ______ combines all items into one value.

โœ… True or False

  1. Recursion can run forever if there is no base case. (True)
  2. map returns a shorter list. (False)
  3. filter returns a longer list. (False)
  4. foldl returns a single value. (True)
  5. We cannot use recursion with lists. (False)

๐Ÿ”˜ Multiple Choice (15)

  1. What does recursion do? A) calls itself B) stops C) adds numbers D) creates lists โ†’ A
  2. What is a base case? A) stop condition B) function C) list D) number โ†’ A
  3. What does map do? A) transforms each item B) keeps some C) combines D) sorts โ†’ A
  4. What does filter do? A) keeps some B) transforms C) combines D) deletes โ†’ A
  5. What does foldl do? A) combines B) transforms C) keeps D) sorts โ†’ A
  6. Which function keeps the same length? A) map B) filter C) fold D) none โ†’ A
  7. Which function can shorten a list? A) filter B) map C) fold D) all โ†’ A
  8. What is (foldl + 0 '(1 2 3))? A) 6 B) 0 C) 1 D) 3 โ†’ A
  9. What is (map double '(1 2)) if double is (* 2 x)? A) '(2 4) B) '(1 2) C) 3 D) error โ†’ A
  10. What is (filter even? '(1 2 3))? A) '(2) B) '(1 3) C) '(1 2 3) D) '() โ†’ A
  11. What happens if recursion has no base case? A) runs forever B) stops C) error D) returns 0 โ†’ A
  12. What is a higher-order function? A) takes a function B) takes numbers C) takes lists D) takes strings โ†’ A
  13. What does (rest '(1 2 3)) return? A) '(2 3) B) 1 C) 3 D) '() โ†’ A
  14. What does (first '(a b)) return? A) a B) b C) (a b) D) error โ†’ A
  15. What is the base case for a list recursion? A) empty list B) first item C) rest D) none โ†’ A

๐Ÿ”— Matching

TermMatch
1. mapA. combines items
2. filterB. transforms each
3. foldC. keeps some
4. recursionD. calls itself

Answers: 1-B, 2-C, 3-A, 4-D

๐Ÿ“ Short Answer

  1. Explain the difference between map and filter.
  2. Why do we need a base case in recursion?
  3. Write a recursive function that returns the sum of all numbers from 1 to n.

๐Ÿ“– Scenario-based Exercises

Scenario: You have a list of temperatures in Celsius. Write a program that converts them to Fahrenheit (C ร— 9/5 + 32) and then finds the average.

Answer: (define (avg lst) (/ (foldl + 0 lst) (length lst))) (avg (map (lambda (c) (+ (* c 1.8) 32)) temps))

๐Ÿ‘ฅ Group Activity

Each group writes a function that takes a list of words and returns a list of their lengths. Use map.

๐Ÿง‘โ€๐Ÿ’ป Individual Activity

Write a recursive function that returns the last element of a list.

๐Ÿ’ฌ Classroom Discussion Questions

  • How is recursion like solving a maze?
  • Why is map useful for data science?
  • What would happen if we didn't have map/filter/fold?

๐Ÿ› ๏ธ Mini Project

Create a "smart filter" for a list of numbers: keep only the numbers that are perfect squares (like 1,4,9,16). Use filter and a helper function.

๐Ÿ“‹ Practical Assignment

Write a program that takes a list of exam scores, removes scores below 40, gives a 5-point bonus to the rest, and finds the total.

๐Ÿ† Challenge Exercise

Write a recursive function that reverses a list. (Hint: append the first item to the reverse of the rest.)

๐Ÿ”‘ Quiz Answers

Multiple choice: 1-A, 2-A, 3-A, 4-A, 5-A, 6-A, 7-A, 8-A, 9-A, 10-A, 11-A, 12-A, 13-A, 14-A, 15-A.

๐ŸŽ Key Takeaways

  • Recursion is a function that calls itself.
  • Base case is essential to stop recursion.
  • map, filter, fold are powerful list tools.
  • Data pipelines combine these functions.
  • You can now process large amounts of data!

๐Ÿš€ Preparation for the Next Module

In Module Four, we will dive into data structures โ€” more ways to organize information. We'll learn about structures, association lists, and trees. You'll be able to build more complex AI systems. Practice your recursion and list functions โ€” they will be your best friends!


๐ŸŽ‰ You've completed Module Three ยท You are now a Racket repetition expert! ๐ŸŽ‰

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (โ‚ฆ2,000 or 20,000 coins), and get a verified certificate with your name on it.

๐ŸŽ“ Sign Up to Get Certified
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
โ†’