← Certified Racket AI Expert Β· Lesson 2 of 8

Module One

πŸ“– 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.
1

Course Outline

Certified Racket AI Expert Β· Course Outline

Certified Racket AI Expert

v2.0 Β· 2026
48h (self-paced) 8 weeks Racket AI Certified

Master AI from the ground up with Racket Β· functional programming, symbolic reasoning, deep learning, and production-grade intelligent systems. This outline covers the complete curriculum for the Certified Racket AI Expert track.

Core syllabus Β· 8 modules
01

Racket essentials & FP

  • Racket syntax, forms, and evaluation
  • Higher-order functions & recursion
  • Macros & domain-specific languages
  • Immutable data & persistent structures
6h
02

Symbolic AI & logic

  • Symbolic reasoning & pattern matching
  • Logic programming (miniKanren)
  • Rule-based systems & expert shells
  • Knowledge representation with Racket
5h
03

Probabilistic & Bayesian

  • Probabilistic programming in Racket
  • Bayesian networks & inference
  • MCMC & sampling techniques
  • Uncertainty quantification
5h
04

Machine learning from scratch

  • Linear regression & gradient descent
  • Logistic regression & classifiers
  • Neural nets in pure Racket (no libs)
  • Backpropagation & autodiff
7h
05

Deep learning with Racket

  • Tensor & matrix operations
  • CNN & RNN architectures
  • Training loops & optimizers
  • Transfer learning & fine-tuning
8h
06

NLP & language models

  • Text processing & tokenization
  • N-grams & embeddings
  • Transformers & attention (Racket)
  • Fine-tuned LMs & generation
6h
07

Reinforcement learning

  • MDPs & dynamic programming
  • Monte Carlo & TD learning
  • DQN & policy gradients
  • Multi‑agent RL
6h
08

Production & ethics

  • Model serialization & serving
  • Racket REST APIs for AI
  • MLOps & monitoring
  • Fairness, bias, explainability
5h

Capstone project: build an end-to-end AI system in Racket β€” from data ingestion to inference β€” with full documentation & performance evaluation.

Certification exam
2

Module One

Module 1 Β· Racket AI Specialist

πŸ”Ή Module One Β· Welcome to Racket & Thinking Like a Computer

Certified Racket AI Specialist Β· Foundation

πŸ“– Module Introduction

Hello, young explorer! πŸ‘‹ Have you ever wondered how your video games work, or how a calculator knows that 2+2=4? In this module, we are going to learn the language of computers. We will use a special language called Racket. Racket is like a magic wand that lets us tell a computer what to do. By the end of this module, you will be able to write your very first computer programs, just like a real AI specialist! We'll start from the very beginning, so don't worry if you have never programmed before. This is your first step to becoming a Racket AI Specialist.

We will learn what a computer is, how it thinks, and how we can give it instructions using Racket. Think of it like learning a new language β€” but instead of talking to people, you will be talking to machines. And the best part? Machines always do exactly what you tell them (even if you make a mistake!).

🧠 Fun fact: Racket is used by real scientists to build artificial intelligence and smart systems!

🎯 Learning Objectives

By the end of this module, you will be able to:

  • βœ”οΈ Explain what a computer is and what a program does.
  • βœ”οΈ Understand why we use Racket for AI.
  • βœ”οΈ Write your first Racket expressions (like 1+1).
  • βœ”οΈ Use numbers and text in Racket.
  • βœ”οΈ Spot the difference between a command and a question.
  • βœ”οΈ Think like a programmer β€” break big problems into small pieces.
  • βœ”οΈ Show confidence to continue learning more!

πŸ“š Warm-up Story Β· The Robot Chef

Imagine you have a robot chef named Racky. Racky is super smart, but it only understands a special language. If you say, "Racky, please make me some jollof rice," Racky will just stare at you. But if you say exactly what to do, step by step, like: "Racky, take a pot. Put oil. Add tomatoes. Add rice. Cook for 20 minutes." β€” then Racky will make perfect jollof rice!

That is exactly what programming is. We give the computer (our robot) a list of clear, simple steps. The computer follows them without getting tired or bored. In this module, we will learn how to give instructions to the computer using Racket.

Let's meet Racket, the language that helps us talk to the computer. Just like learning "hello" and "goodbye" in a new language, we'll start with small words and build up to big, amazing programs.

   +-----------------+
   |   You (coder)   |
   +--------+--------+
            |
            |  (write Racket code)
            V
   +-----------------+
   |   Computer      |
   |  (Racket reads  |
   |   and follows)  |
   +-----------------+
            |
            V
   +-----------------+
   |  Result: answer,|
   |  drawing, game  |
   +-----------------+
  

🧩 Main Lessons

Lesson 1 Β· What is a Computer, Really?

Definition: A computer is a machine that follows instructions to do work. It can add numbers, show pictures, and play music β€” but only if we tell it how.

Why it matters: To be an AI specialist, you must understand what a computer can and cannot do.

Simple explanation: Think of a computer as a very fast, very dumb worker. It does exactly what you say, no more, no less. If you say "add 2 and 3", it answers 5. If you say "make a cake", it doesn't know what that means (unless you give it a cake recipe).

Real-life example: A calculator is a small computer. You press 2+3, it shows 5.

School example: In math class, your teacher gives you a problem; you solve it. A computer needs every single step.

Home example: When you set the microwave to 2 minutes and press start, the microwave follows that instruction exactly.

Nigerian example: Think of a POS machine. When you enter your PIN and amount, the machine follows the instructions to give you cash.

Illustration:

   [Your instruction]  --->  [Computer]  --->  [Result]
       "2 + 3"         --->    adds      --->     5
  
πŸ“Œ Mini summary: A computer is a hardworking machine that follows instructions. We need to give it clear, small steps.

Lesson 2 Β· What is a Programming Language?

Definition: A programming language is a special way to write instructions that a computer can understand.

Why important: We cannot speak "computer" directly, so we use a programming language as a translator.

Simple explanation: Just like we use English, Yoruba, or Hausa to talk to people, we use a programming language to talk to computers. Racket is one of these languages.

Real-life: English, French, and Spanish are languages for people. Python, Racket, Java are languages for computers.

School: In your school, you might learn English, Maths, and Science. In programming, you learn a language like Racket.

Home: Your mum speaks to you in your mother tongue; you speak to the computer in Racket.

Nigerian: In Nigeria, we have many languages: Yoruba, Igbo, Hausa. Racket is just another language β€” but for computers.

Illustration:

   +-------------+      +----------------+      +-----------+
   |  You write  | ---> |  Racket reads  | ---> | Computer  |
   |  (+ 2 3)    |      |  and translates|      | answers 5 |
   +-------------+      +----------------+      +-----------+
  
πŸ“Œ Mini summary: A programming language is like a bridge between you and the computer. Racket is our bridge.

Lesson 3 Β· Getting to Know Racket

Definition: Racket is a friendly programming language that is great for learning and for building smart AI systems.

Why Racket? It is simple, powerful, and teaches you to think clearly β€” exactly what an AI specialist needs.

Simple explanation: Racket is like a toy box. It has lots of tools (functions) to play with numbers, words, and even draw pictures.

Real-life: Many top universities use Racket to teach computer science.

School: Imagine if your maths teacher gave you a magic pen that could solve any problem. That's Racket.

Home: If you wanted to teach your younger sibling how to count, you would use simple words. Racket uses simple words too.

Nigerian: Racket is like the "Ube" (Pear) of programming languages β€” sweet, nutritious, and everyone can enjoy it.

Illustration:

   Racket language
         |
         V
   +-------------+
   |  ( + 5 3 )  |   -- means add 5 and 3
   +-------------+
         |
         V
      answer: 8
  
πŸ“Œ Mini summary: Racket is a fun, clear language that helps us talk to computers. We will use it to build amazing things.

Lesson 4 Β· Numbers and Math in Racket

Definition: Numbers are the most basic things we use in Racket. We can add, subtract, multiply, and divide.

Why important: AI often uses math to make decisions β€” like scoring a game or predicting the weather.

Simple explanation: In Racket, we write math like this: (+ 2 3) means 2+3. The + is the operation, and the numbers are after it.

Real-life: When you buy a snack for 50 Naira and give 100 Naira, the cashier subtracts: 100 - 50 = 50.

School: In class, you write 3 + 4 = 7. In Racket, we write (+ 3 4) and it gives 7.

Home: If you have 5 oranges and eat 2, you have 3 left. In Racket: (- 5 2) β†’ 3.

Nigerian: If you buy 10 sachets of water and share 4, you have 6 left. Racket: (- 10 4).

Illustration:

   (+ 2 3)   β†’   5
   (- 9 4)   β†’   5
   (* 2 3)   β†’   6
   (/ 10 2)  β†’   5
  
πŸ“Œ Mini summary: Racket can do all kinds of math. We just put the operator first, then the numbers.

Lesson 5 Β· Words (Strings) in Racket

Definition: A string is a piece of text, like "Hello" or "Racket is fun". In Racket, we put quotes around strings.

Why it matters: AI systems often need to understand and generate text β€” like chatbots.

Simple explanation: If you want to say your name, you write "Chidi" in Racket. The quotes tell Racket this is a word, not a math instruction.

Real-life: When you send a text message, that's a string.

School: Your teacher might write "Good job!" on your work. That's a string.

Home: You might say "I love rice" β€” in Racket that is "I love rice".

Nigerian: "Jollof rice is delicious" β€” Racket stores it as "Jollof rice is delicious".

Illustration:

   "Hello"   β†’  a string
   "123"     β†’  a string (not a number)
   (+ 2 3)   β†’  math
   (+ "2" 3) β†’  error (can't mix string and number)
  
πŸ“Œ Mini summary: Strings are text. We use quotes to tell Racket we mean words, not numbers.

Lesson 6 Β· The Racket Way of Thinking

Definition: In Racket, we write everything in a "prefix" style β€” the operator (like + or -) comes first, then the values.

Why it's cool: This makes Racket very consistent. Every instruction looks similar: (verb thing1 thing2 ...).

Simple explanation: Instead of saying "2 plus 3", we say "plus 2 3" β€” like Yoda from Star Wars! "Add you must, 2 and 3."

Real-life: Imagine giving commands to a robot: "Walk forward 2 steps" is like (walk 2).

School: When your teacher says "Read page 10", that's (read page 10) in Racket style.

Home: "Eat 3 bananas" β†’ (eat 3 bananas).

Nigerian: "Buy 5 loaves of bread" β†’ (buy 5 bread).

Illustration:

   English style:  2 + 3
   Racket style:   (+ 2 3)

   English:        "Hello" + " World"
   Racket:         (string-append "Hello" " World")
  
πŸ“Œ Mini summary: In Racket, we always put the action first, then the things we act on.

Lesson 7 Β· Storing Things with Variables

Definition: A variable is like a box that holds a value. You can put a number or a string inside, and give it a name.

Why important: Variables let us remember things, so we can use them again later.

Simple explanation: Imagine you have a box labelled "age" and you put 10 inside. Now whenever you say age, Racket knows you mean 10.

Real-life: Your school bag has a name tag β€” that's like a variable. The contents are the value.

School: Your locker number stores your books.

Home: A jar labelled "sweets" β€” if you put 5 sweets in, the label tells you.

Nigerian: A "kolo" (piggy bank) with "savings" β€” when you put money in, the name tells you what it is.

Illustration:

   (define age 10)   ; creates a variable called age with value 10
   age   β†’ 10
   (define name "Ade") ; variable name holds "Ade"
   name  β†’ "Ade"
  
πŸ“Œ Mini summary: Variables store information. We use define to create them.

Lesson 8 Β· Making Decisions (if statements)

Definition: An if statement lets the computer make choices: if something is true, do one thing; otherwise, do something else.

Why important: AI needs to make decisions β€” like if it's raining, carry an umbrella.

Simple explanation: If you are hungry, eat. Otherwise, play. Racket can do this too.

Real-life: If the traffic light is red, stop; if green, go.

School: If you score above 70, you get an A. Otherwise, you get a B.

Home: If you finish your homework, you can watch TV.

Nigerian: If the price of beans is cheap, buy more; otherwise, buy less.

Illustration:

   (if (< 5 10) "smaller" "bigger")  β†’ "smaller"
   (if (> 5 10) "bigger" "smaller")  β†’ "smaller"
  
πŸ“Œ Mini summary: If helps the computer decide which path to take.

Lesson 9 Β· Creating Your Own Commands (Functions)

Definition: A function is a new command that you create. You give it a name and tell it what to do.

Why it matters: Functions let you reuse code. Once you make a command, you can use it many times.

Simple explanation: Imagine you invent a dance called "The Racket". You teach it to your friend once, then they can do it anytime.

Real-life: A recipe is like a function. Once you write it, you can cook the dish many times.

School: A maths formula like area = length Γ— width is a function.

Home: A chore routine: "tidy room" means pick up toys, make bed.

Nigerian: "Make Jollof" β€” a function that includes steps: fry, add rice, cook.

Illustration:

   (define (square x) (* x x))   ; define a function to square a number
   (square 5)  β†’ 25
   (square 3)  β†’ 9
  
πŸ“Œ Mini summary: Functions are your own custom commands. They make programming powerful.

Lesson 10 Β· Lists – Putting Things in Order

Definition: A list is a collection of things, like a shopping list. In Racket, we use ' (1 2 3).

Why important: AI often works with groups of data β€” like all the scores of a game.

Simple explanation: It's like a queue in school β€” everyone stands in a line.

Real-life: A grocery list: eggs, milk, bread.

School: A list of students in your class.

Home: A list of chores: sweep, dust, clean.

Nigerian: A list of items to buy at the market: yam, pepper, onions.

Illustration:

   '(1 2 3 4)          ; a list of numbers
   '("apple" "banana") ; a list of strings
   (first '(1 2 3))    β†’ 1
   (rest '(1 2 3))     β†’ (2 3)
  
πŸ“Œ Mini summary: Lists hold multiple values in order. We can take the first or the rest.

Lesson 11 Β· Putting It All Together – Our First AI Program

We now know enough to write a tiny AI: a program that greets you and tells you if you can watch TV. Let's combine variables, if, and functions!

   (define name "Zainab")
   (define age 10)
   (define (can-watch-tv? age) (if (> age 8) "Yes, you may" "No, too young"))
   (string-append "Hello " name ", " (can-watch-tv? age))
   β†’ "Hello Zainab, Yes, you may"
  

This is a real program! It uses a variable, a function, and an if statement. You just built a tiny AI!

πŸ“Œ Mini summary: We can combine everything to make useful programs β€” this is the start of AI!

πŸ“– Key Vocabulary

  • Computer: A machine that follows instructions.
  • Program: A set of instructions for the computer.
  • Racket: A programming language we use to talk to computers.
  • String: Text inside quotes, like "hello".
  • Variable: A box with a name that stores a value.
  • Function: A custom command you create.
  • List: A collection of items in order.
  • If statement: A way to make decisions in code.

🧠 Important Concepts

  • Precision: Computers are dumb β€” they need exact instructions.
  • Order: Instructions run one after another.
  • Abstraction: Hiding details inside functions.
  • Reuse: Functions let us reuse code again and again.

πŸ“˜ Step-by-Step Explanations

How to write your first Racket program:

  1. Open Racket (DrRacket).
  2. Type (+ 5 6) in the interactions window.
  3. Press Enter. See 11 appear!
  4. Now type (define age 12).
  5. Type age β€” Racket shows 12.
  6. Type (define (double x) (* x 2)).
  7. Type (double 5) β€” you get 10!

🌍 Real-life Examples

  • ATMs: they follow instructions to dispense cash.
  • Traffic lights: they use decision logic (if green, go).
  • Spell-checkers: they look at lists of words.

πŸ‡³πŸ‡¬ Nigerian Examples

  • Mobile banking apps: they use functions to transfer money.
  • Jollof rice recipe: a function that makes food.
  • School attendance: a list of student names.

🎈 Fun Examples

  • If you have 10 candies and eat 3, how many left? Racket: (- 10 3)
  • Make a variable called "bestFood" and set it to "Pizza".
  • Write a function called "shout" that takes a word and adds "!!!" at the end.

🏠 Everyday Examples

  • A recipe: functions.
  • A to-do list: lists.
  • An alarm clock: if time = 7am, ring.

πŸ§‘β€πŸ« Teacher Notes

Encourage learners to type every example themselves. Relate everything to daily life. Use physical objects (like boxes for variables). Emphasize that mistakes are normal β€” debugging is part of the fun.

πŸ‘ͺ Parent Tips

Ask your child to teach you what they learned. Let them show you how Racket adds numbers. Celebrate every small success. Learning to code is like learning a sport β€” practice, patience, and fun!

🌟 Interesting Facts

  • The first computer was as big as a room!
  • Racket was created by a team at a university.
  • AI can now play chess better than any human.

πŸ€” Did You Know?

Racket was originally made for teaching, so it's perfect for beginners like you. And many AI researchers use it to test new ideas!

🧾 Remember This

  • Computers follow instructions exactly.
  • Racket uses prefix notation: operator first.
  • Variables store things.
  • Functions let you create new commands.
  • Lists hold groups of things.

⚠️ Common Mistakes

  • Forgetting the quote around strings: "hello" not hello.
  • Using = instead of equal? for comparing.
  • Mixing up the order: (+ 2 3) is correct, (2 + 3) is not.
  • Forgetting to close parentheses: (+ 2 3 is missing a ).

βœ… Best Practices

  • Always use descriptive names for variables: age not x.
  • Break big problems into small functions.
  • Test each small part before moving on.

πŸ“Š ASCII Illustrations

   +--------+      +--------+      +--------+
   |  Input | ---> | Racket | ---> | Output |
   +--------+      +--------+      +--------+
       ( + 5 3 )   computes         8
  
   Flow of a program:
   Start β†’ Get Input β†’ Process β†’ Show Result β†’ End
  

πŸ“‹ Comparison Table

ConceptEnglish analogyRacket example
VariableBox with label(define age 12)
FunctionRecipe(define (square x) (* x x))
ListShopping list'(1 2 3)
IfDecision(if (> age 8) "big" "small")

πŸ“Œ End-of-Module Summary

Wow! You've learned so much. You now know what a computer is, how to talk to it using Racket, how to use numbers and words, how to store things in variables, make decisions with if, create your own functions, and group things in lists. You've written your first tiny AI program. You are on your way to becoming a Certified Racket AI Specialist!

❓ Frequently Asked Questions (10)

  1. What is Racket? β€” A programming language for beginners and experts.
  2. Is Racket hard? β€” No! It's very friendly.
  3. Do I need a fast computer? β€” No, any computer works.
  4. Can I use Racket for games? β€” Yes, you can.
  5. Is Racket free? β€” Yes, completely free.
  6. What is a string? β€” Text inside quotes.
  7. What is a variable? β€” A named box for a value.
  8. What does (define) do? β€” It creates a variable or function.
  9. Can I make mistakes? β€” Yes, and it's okay. That's how we learn.
  10. What's next? β€” We'll learn more in Module Two!

πŸ“ Review Questions (15)

  1. What is a computer?
  2. What is a programming language?
  3. What does (+ 3 4) do?
  4. How do you write "hello" in Racket?
  5. What is a variable?
  6. How do you create a variable named age with value 12?
  7. What is a function?
  8. Write a function that doubles a number.
  9. What is a list?
  10. How do you make a list of (1 2 3) in Racket?
  11. What does (if (> 5 3) "yes" "no") return?
  12. What is a string?
  13. Why is Racket good for beginners?
  14. What does (rest '(a b c)) return?
  15. Write a program that adds 5 and 7.

✏️ Fill-in-the-Blank

  1. A ______ is a machine that follows instructions.
  2. In Racket, text is written inside ______.
  3. The command to create a variable is ______.
  4. A ______ holds multiple values in order.
  5. The (if) statement helps us make ______.

βœ… True or False

  1. Computers can think for themselves. (False)
  2. Racket uses prefix notation. (True)
  3. Strings are numbers. (False)
  4. Functions can reuse code. (True)
  5. Lists are not useful in AI. (False)

πŸ”˜ Multiple Choice (15)

  1. What does (+ 2 3) return? A) 5 B) 23 C) error D) 6 β†’ A
  2. How do you write a string? A) "hello" B) hello C) 'hello D) (hello) β†’ A
  3. Which creates a variable? A) (define x 5) B) (set x 5) C) (var x 5) D) (x 5) β†’ A
  4. What is a function? A) A machine B) A command you make C) A number D) A list β†’ B
  5. Which is a list? A) (1 2 3) B) [1 2 3] C) {1 2 3} D) "1 2 3" β†’ A (with quote)
  6. What does (if (< 3 5) "small" "big") return? A) small B) big C) error D) 5 β†’ A
  7. What is Racket? A) A game B) A programming language C) A food D) A country β†’ B
  8. What does (first '(a b c)) return? A) a B) b C) c D) (a b c) β†’ A
  9. What is a variable? A) A box with a name B) A number C) A string D) A list β†’ A
  10. Can functions call other functions? A) Yes B) No C) Maybe D) Never β†’ A
  11. What does (string-append "Hello" " World") do? A) Adds numbers B) Joins text C) Multiplies D) Error β†’ B
  12. Which is NOT a Racket operator? A) + B) - C) * D) Γ· β†’ D (uses /)
  13. What do we need to close after an expression? A) Parentheses B) Brackets C) Curly braces D) Quotes β†’ A
  14. Is Racket free? A) Yes B) No C) Maybe D) Expensive β†’ A
  15. What does (rest '(1 2 3)) return? A) 1 B) (2 3) C) (1 2) D) 3 β†’ B

πŸ”— Matching Exercises

TermMatch
1. (define x 10)A. Function
2. (define (add a b) (+ a b))B. Variable
3. '(a b c)C. List
4. "hello"D. String

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

πŸ“ Short Answer

  1. Explain what a computer does in your own words.
  2. Why do we use Racket?
  3. Give an example of a function you could make.

πŸ“– Scenario-based Exercises

Scenario: You are building a simple bot for a shop. It should take the item price and quantity and calculate the total. How would you do it in Racket?

Answer: (define (total price qty) (* price qty))

πŸ‘₯ Group Activity

In groups of 3, pretend you are a computer. One person gives instructions like "(+ 4 5)", another computes the answer, and the third checks if it's correct. Take turns.

πŸ§‘β€πŸ’» Individual Activity

Write a Racket expression that adds 10 and 20, multiplies the result by 2, and stores it in a variable called "result".

πŸ’¬ Classroom Discussion Questions

  • Why is it important to give clear instructions to a computer?
  • Can you think of a real-life example where a computer makes a decision?
  • How is learning Racket similar to learning a new language?

πŸ› οΈ Mini Project

Create a simple "greeting bot" that asks for your name and says hello. Use a variable, a string, and display a message. (You can use (display) or just return a string.)

πŸ“‹ Practical Assignment

Write a Racket program that takes your age and tells you if you are old enough to ride a rollercoaster (age > 12).

πŸ† Challenge Exercise

Write a function that takes a list of numbers and returns the sum of all the numbers. (Hint: you can use recursion or the built-in (apply + list).)

πŸ”‘ Quiz Answers

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

🎁 Key Takeaways

  • Computers need clear, exact instructions.
  • Racket is a fun and powerful language.
  • Variables store information.
  • Functions help us reuse code.
  • We made our first AI program!

πŸš€ Preparation for the Next Module

In Module Two, we will dive deeper into decision-making and start building more intelligent programs. We'll learn about logic, more math, and how to make our programs "remember" things. Get ready to create a tiny chatbot!

Before then, practice writing simple Racket expressions, create your own variables, and write at least three functions. The more you practice, the more it will stick.


πŸŽ‰ You've completed Module One Β· Great job, future AI specialist! πŸŽ‰

3

M0dule Two

Module 2 Β· Racket AI Specialist – Decisions & Logic

🧠 Module Two · Decisions, Logic & Smarter Programs

Certified Racket AI Specialist Β· Building Intelligence

πŸ“– Module Introduction

Hello again, young programmer! πŸ‘‹ In Module One, we learned how to talk to the computer using Racket. We used numbers, words, and even made our own commands. But a computer that only adds numbers is like a robot that can only wave β€” useful, but not very smart.

In this module, we will teach our computer to think and make decisions. We will learn about logic β€” the rules of true and false. We will also learn how to compare things, make choices, and repeat actions. By the end, your programs will be able to decide what to do based on information, just like a real AI!

πŸ€– Did you know? The "AI" in Artificial Intelligence is all about making computers that can make decisions, just like we do!

🎯 Learning Objectives

After this module, you will be able to:

  • βœ”οΈ Understand what true and false mean in Racket.
  • βœ”οΈ Compare numbers and words using operators like >, <, =.
  • βœ”οΈ Write if statements that make decisions.
  • βœ”οΈ Use cond (a multi-way if) to handle many choices.
  • βœ”οΈ Combine conditions with and, or, not.
  • βœ”οΈ Create programs that respond differently based on input.
  • βœ”οΈ Think logically and break down big decisions into steps.

πŸ“š Warm-up Story Β· The Magic Lamp

Imagine you find a magic lamp. When you rub it, a genie appears. But this genie is very strict β€” it only follows rules. You tell the genie: "If I say the magic word, give me a gift. Otherwise, do nothing." The genie checks: did you say the word? If yes, it gives you a gift. If no, it stays still.

That is exactly what an if statement does in Racket. It checks a condition. If the condition is true, it does one thing. If false, it does something else (or nothing).

In this module, we will give our programs the power to make decisions like that genie. We'll also learn how to combine decisions β€” like: "If it's raining AND I have an umbrella, go out. Otherwise, stay inside."

   +-------------------+
   |   Condition       |
   | (is it true?)     |
   +--------+----------+
            |
     +------+------+
     |             |
    YES           NO
     |             |
     V             V
  Do action A   Do action B
  

🧩 Main Lessons

Lesson 1 Β· True and False – The Building Blocks of Logic

Definition: In Racket, true and false are values that tell us if something is correct or not. We write #t for true and #f for false.

Why important: Every decision a computer makes is based on true or false. If it's true, do one thing. If false, do another.

Simple explanation: Think of a light switch. On = true, Off = false. The computer can only be in one of these two states for any question.

Real-life example: "Is the sky blue?" – yes (true). "Is water dry?" – no (false).

School example: "Is 2 + 2 equal to 4?" – true. "Is 5 less than 3?" – false.

Home example: "Is it time for dinner?" – maybe true or false depending on the clock.

Nigerian example: "Is Lagos a city in Nigeria?" – true. "Is Abuja in Ghana?" – false.

Illustration:

   #t   β†’  True (yes, correct)
   #f   β†’  False (no, not correct)

   ( = 5 5 )  β†’  #t
   ( = 5 7 )  β†’  #f
  
πŸ“Œ Mini summary: True and false are like yes/no answers. Racket uses #t and #f.

Lesson 2 Β· Comparing Numbers ( > , < , = )

Definition: We compare numbers using operators: > (greater), < (less), = (equal), >= (greater or equal), <= (less or equal).

Why important: AI uses comparisons all the time – e.g., if a player's score is higher than the high score, update it.

Simple explanation: These are like the maths signs you know: > means bigger than, < means smaller than, = means same as.

Real-life: "Your age is greater than 10?" – check if you are older than 10.

School: "Is 80 greater than 70?" – yes, so you get a better grade.

Home: "Do we have more than 5 apples?" – check the count.

Nigerian: "Is the price of groundnut oil less than 2000 Naira?" – check to buy.

Illustration:

   (> 10 5)   β†’  #t   (10 is greater than 5)
   (< 4 9)    β†’  #t   (4 is less than 9)
   (= 7 7)    β†’  #t   (7 is equal to 7)
   (>= 8 8)   β†’  #t   (8 is greater or equal to 8)
  
πŸ“Œ Mini summary: Comparison operators test numbers and return #t or #f.

Lesson 3 Β· Comparing Strings (equal? and string=?)

Definition: To compare words (strings), we use equal? or string=? to check if they are exactly the same.

Why important: AI often needs to check if a user said a certain word, e.g., "yes" or "no".

Simple explanation: It's like asking: "Is your name the same as my friend's name?"

Real-life: If you type "hello", the computer checks if that's equal to "hello".

School: "Is the answer 'B'?" – check the string.

Home: "Did you say 'please'?" – check the word.

Nigerian: "Did you say 'Abuja'?" – check the city name.

Illustration:

   (equal? "hello" "hello")  β†’  #t
   (equal? "hello" "goodbye")β†’  #f
   (string=? "Ade" "Ade")    β†’  #t
  
πŸ“Œ Mini summary: Use equal? or string=? to check if two strings are the same.

Lesson 4 Β· The If Statement – Making Decisions

Definition: An if statement checks a condition. If the condition is true, it does the first thing; if false, it does the second thing.

Why important: This is the most common way to make decisions in programs.

Simple explanation: If it's raining, take an umbrella; otherwise, don't.

Real-life: If you are hungry, eat. Otherwise, play.

School: If you have homework, do it; otherwise, watch TV.

Home: If the light is on, turn it off; else, leave it.

Nigerian: If you have money, buy meat pie; otherwise, buy puff-puff.

Illustration:

   (if ( > 5 3 )    ; condition: 5 > 3 ?
       "yes, it is"  ; true branch
       "no, it isn't") ; false branch
   β†’ "yes, it is"
  
πŸ“Œ Mini summary: If lets the computer choose between two actions based on a condition.

Lesson 5 Β· The Cond Statement – Many Choices

Definition: cond is like an if statement but with many choices. It checks each condition one by one, and runs the first that is true.

Why important: Sometimes we have more than two options – like choosing a meal from a menu.

Simple explanation: It's like a school grading system: if score β‰₯ 90 β†’ A, else if β‰₯ 80 β†’ B, else β†’ C.

Real-life: Traffic light: red β†’ stop, yellow β†’ wait, green β†’ go.

School: If you get 100, you get a star; if 80, a check; else, try again.

Home: If day is Monday, eat rice; Tuesday, eat yam; otherwise, eat beans.

Nigerian: If you are in Lagos, take the bus; if in Abuja, take a taxi; else, walk.

Illustration:

   (cond
     [(> 90 100) "A"]   ; if false, skip
     [(> 75 100) "B"]   ; false
     [else "C"])        ; else runs if nothing else true
   β†’ "C"
  
πŸ“Œ Mini summary: Cond is for multiple options. It picks the first true condition.

Lesson 6 Β· Combining Conditions with AND, OR, NOT

Definition: We can combine true/false values using and, or, not. and is true only if all are true; or is true if at least one is true; not flips true to false and false to true.

Why important: Real decisions often need multiple conditions: "If it's sunny AND I'm free, I'll play outside."

Simple explanation: AND: both must be true. OR: at least one true. NOT: the opposite.

Real-life: You can watch TV if you finish homework AND your mom says yes.

School: You get a prize if you score 100 OR you are the best student.

Home: You can eat if the food is ready AND you set the table.

Nigerian: You can go to the market if you have money AND it's not raining.

Illustration:

   (and #t #t)   β†’  #t
   (and #t #f)   β†’  #f
   (or #t #f)    β†’  #t
   (or #f #f)    β†’  #f
   (not #t)      β†’  #f
   (not #f)      β†’  #t
  
πŸ“Œ Mini summary: AND, OR, NOT help us build complex conditions.

Lesson 7 Β· Using Logic to Make a Smart Calculator

Let's build a calculator that can add, subtract, multiply, or divide based on the operator you choose. We'll use cond to pick the operation.

   (define (calculate op a b)
     (cond
       [(equal? op "add") (+ a b)]
       [(equal? op "sub") (- a b)]
       [(equal? op "mul") (* a b)]
       [(equal? op "div") (/ a b)]
       [else "unknown operation"]))
   (calculate "add" 5 3)   β†’ 8
   (calculate "mul" 4 2)   β†’ 8
  
πŸ“Œ Mini summary: We can use logic to choose between many actions.

Lesson 8 Β· The Number of Choices – Using else

Definition: In cond, we can use else as the last option to catch anything that wasn't caught earlier.

Why important: It's like a safety net – if nothing matches, do this.

Simple explanation: "If you have A, good; if B, okay; else, try again."

Real-life: If you have a ticket, enter; else, buy one.

School: If you answer all questions, you pass; else, you need to study more.

Home: If you finish your vegetables, you get dessert; else, no dessert.

Nigerian: If the bus arrives, board; else, wait.

Illustration:

   (cond
     [(= 5 6) "not"]
     [else "everything else"])
   β†’ "everything else"
  
πŸ“Œ Mini summary: else catches all remaining cases.

Lesson 9 Β· Nesting If – Decisions Inside Decisions

Definition: You can put an if or cond inside another one. This is called nesting.

Why important: Some decisions depend on other decisions, like: "If you have money, then if the shop is open, buy something."

Simple explanation: It's like a game where you unlock a door, and behind that door is another door.

Real-life: If you have a phone, then if it has battery, you can call.

School: If you pass maths, then if you pass science, you get a prize.

Home: If it's your birthday, then if we have cake, we eat cake.

Nigerian: If you have transport money, then if the bus is available, go to the market.

Illustration:

   (if (> age 12)
       (if (equal? name "Ade")
           "you are Ade and older"
           "you are older but not Ade")
       "you are young")
  
πŸ“Œ Mini summary: Nesting lets us make deeper decisions.

Lesson 10 Β· Building a Decision Tree – Flowcharts

A decision tree is a picture of all the possible choices and their outcomes. It helps us plan our program.

Example: A chatbot that greets people based on the time of day.

   Start
     |
     V
   Ask: what is the hour?
     |
     V
   +---------+---------+---------+
   |         |         |         |
  Morning  Afternoon  Evening  Night
   |         |         |         |
   V         V         V         V
  "Good      "Good     "Good     "Good
   morning"   afternoon" evening"  night"
  
πŸ“Œ Mini summary: Decision trees help us plan complex decisions.

Lesson 11 Β· Boolean Functions – Returning True/False

Definition: A function that returns #t or #f is called a boolean function. We use them to check conditions.

Why important: They help us build reusable tests.

Simple explanation: It's like a yes/no question that we can ask many times.

Real-life: A function that checks if a number is even: (even? 4) β†’ #t.

School: A function that checks if a student passed: (pass? score) β†’ #t if score β‰₯ 50.

Home: A function that checks if the door is locked.

Nigerian: A function that checks if someone is over 18 to vote.

Illustration:

   (define (even? n) (= 0 (remainder n 2)))
   (even? 4)  β†’ #t
   (even? 5)  β†’ #f
  
πŸ“Œ Mini summary: Boolean functions are tests that return #t or #f.

Lesson 12 Β· Putting It All Together – A Smart Decision Program

We now build a program that asks for your age and tells you if you can drive, vote, or just play.

   (define (age-check age)
     (cond
       [(< age 12) "You are too young to drive or vote. Play games!"]
       [(< age 18) "You can't vote yet, but maybe you can learn to drive."]
       [(< age 60) "You can drive and vote!"]
       [else "You are a wise elder. Rest and enjoy."]))
   (age-check 10)  β†’ "You are too young..."
   (age-check 20)  β†’ "You can drive and vote!"
  

This is a real AI-like program that gives different answers based on your age. You are now building intelligence!

πŸ“Œ Mini summary: We combined many ideas to build a smart age advisor.

πŸ“– Key Vocabulary

  • True (#t): Correct, yes.
  • False (#f): Incorrect, no.
  • Condition: A question that is either true or false.
  • If statement: A command that runs code based on a condition.
  • Cond: A way to check many conditions.
  • AND: True only if everything is true.
  • OR: True if at least one is true.
  • NOT: Flips true to false and false to true.
  • Nesting: Putting one decision inside another.
  • Boolean: A value that is either true or false.

🧠 Important Concepts

  • Truth values: Everything in logic is either #t or #f.
  • Short-circuiting: In AND, if the first is false, Racket doesn't check the rest.
  • Decision trees: Visual way to plan logic.
  • Reusability: Boolean functions can be reused many times.

πŸ“˜ Step-by-Step Explanations

How to write a decision program:

  1. Identify what decision you need (e.g., can I go out?).
  2. List all the conditions (e.g., is it sunny? is it free?).
  3. Write the conditions using >, <, =, equal? etc.
  4. Use if or cond to choose between actions.
  5. Test with different inputs.

🌍 Real-life Examples

  • ATM: if you enter correct PIN, give money; else, block card.
  • Spam filter: if email contains certain words, mark as spam.
  • Games: if player reaches score 100, you win.

πŸ‡³πŸ‡¬ Nigerian Examples

  • Bank transfer: if you have enough balance, send money; else, show error.
  • Traffic light at a busy junction: if red, stop; if green, go.
  • Smart irrigation: if soil is dry, turn on water; else, keep off.

🎈 Fun Examples

  • If your pet is hungry, feed it; else, play with it.
  • If your friend says "hello", reply "hello"; if "bye", say "bye".
  • If a number is even, say "even"; else, say "odd".

🏠 Everyday Examples

  • Waking up: if alarm rings, get up; else, sleep.
  • Cooking: if water is boiling, add pasta; else, wait.
  • Homework: if it's finished, play; else, continue.

πŸ§‘β€πŸ« Teacher Notes

Emphasize that logic is everywhere. Use physical examples: "If I clap, you sit down. Else, stand up." Use cards with #t and #f. Let students write small programs with if and cond. Encourage them to test different inputs.

πŸ‘ͺ Parent Tips

Ask your child to explain the difference between AND and OR. Play the "if game" at home: "If you clean your room, then you can have a snack." This builds logical thinking. Celebrate when they get the logic right!

🌟 Interesting Facts

  • Boolean logic is named after George Boole, a mathematician.
  • Every modern computer uses boolean logic at its core.
  • AI uses logic to solve complex problems like disease diagnosis.

πŸ€” Did You Know?

Racket's cond is so flexible that you can write entire programs using only cond and recursion. Many AI systems are built using these same ideas!

🧾 Remember This

  • #t means true, #f means false.
  • Comparisons return #t or #f.
  • if chooses between two paths.
  • cond handles many paths.
  • AND, OR, NOT combine conditions.

⚠️ Common Mistakes

  • Using = to compare strings – use equal?.
  • Forgetting that and and or are operators, not keywords.
  • Not using else in cond – your program might return nothing.
  • Nesting too deeply – keep it simple.

βœ… Best Practices

  • Always make your conditions clear.
  • Use cond for more than 3 options.
  • Write tiny functions that test one thing.
  • Test both true and false cases.

πŸ“Š ASCII Illustrations

   Decision Flow:
   +---------+     +--------+     +--------+
   | Condition | --> | #t?   | --> | Action1 |
   +---------+     +--------+     +--------+
                     |
                     V
                   +--------+     +--------+
                   | #f?    | --> | Action2 |
                   +--------+     +--------+
  
   AND logic:
   Input1 ---+
              AND ---> Output
   Input2 ---+
  

πŸ“‹ Comparison Table

OperatorMeaningExampleResult
>greater than(> 10 5)#t
<less than(< 2 5)#t
=equal (numbers)(= 3 3)#t
equal?equal (any type)(equal? "hi" "hi")#t
andboth true(and #t #t)#t
orat least one true(or #f #t)#t
notflips(not #t)#f

πŸ“Œ End-of-Module Summary

Amazing! You've completed Module Two. You now know how to make your programs decide things. You learned about true/false, comparison operators, if, cond, and logic combiners. You even built a smart age advisor. You are thinking like a real programmer. These decision-making skills are the heart of artificial intelligence. Every AI system, from self-driving cars to smart assistants, uses these same logical building blocks.

❓ Frequently Asked Questions (10)

  1. What is the difference between if and cond? β€” if is for two choices; cond is for many.
  2. What does #t mean? β€” true, yes.
  3. What does #f mean? β€” false, no.
  4. Can I compare strings with =? β€” No, use equal? or string=?.
  5. What is else? β€” It catches any remaining cases in cond.
  6. What does and do? β€” It's true only if all parts are true.
  7. What does or do? β€” It's true if at least one part is true.
  8. What does not do? β€” It flips true to false and false to true.
  9. Can I put if inside if? β€” Yes, that's nesting.
  10. Why is logic important for AI? β€” AI uses logic to make decisions and solve problems.

πŸ“ Review Questions (15)

  1. What is #t in Racket?
  2. What operator checks if two numbers are equal?
  3. How do you check if two strings are equal?
  4. What does (if (> 5 3) "yes" "no") return?
  5. Write a cond that gives "A" for 90+, "B" for 80+, else "C".
  6. What does (and #t #f) return?
  7. What does (or #f #f) return?
  8. What does (not #f) return?
  9. What is nesting?
  10. Why do we use else in cond?
  11. Write a function that returns #t if a number is positive.
  12. What is a boolean function?
  13. How do you compare 5 and 7 to see if 5 is less?
  14. What is a decision tree?
  15. Give an everyday example of an if statement.

✏️ Fill-in-the-Blank

  1. #t stands for ______.
  2. The operator ______ checks if two numbers are equal.
  3. ______ is used to check many conditions.
  4. ______ flips true to false.
  5. We use ______ to combine two conditions where both must be true.

βœ… True or False

  1. #f means true. (False)
  2. You can use = to compare strings. (False)
  3. Cond can handle more than two choices. (True)
  4. AND returns true if at least one is true. (False – that's OR)
  5. Nesting is putting one if inside another. (True)

πŸ”˜ Multiple Choice (15)

  1. What does (> 8 5) return? A) #t B) #f C) 8 D) 5 β†’ A
  2. What does (= 5 5) return? A) #t B) #f C) 5 D) error β†’ A
  3. What does (equal? "cat" "cat") return? A) #t B) #f C) "cat" D) error β†’ A
  4. Which statement has two choices? A) cond B) if C) and D) or β†’ B
  5. What does (and #t #f) return? A) #t B) #f C) #t/#f D) error β†’ B
  6. What does (or #f #t) return? A) #t B) #f C) #t/#f D) error β†’ A
  7. What does (not #t) return? A) #t B) #f C) #f/#t D) error β†’ B
  8. Which is used for many choices? A) if B) cond C) and D) not β†’ B
  9. What is #t? A) true B) false C) number D) string β†’ A
  10. What does (string=? "Ade" "Ade") return? A) #t B) #f C) "Ade" D) error β†’ A
  11. What is a boolean function? A) returns #t or #f B) adds numbers C) prints text D) makes lists β†’ A
  12. What is nesting? A) putting if inside if B) using cond C) using and D) using or β†’ A
  13. What does (if (< 3 5) "small" "big") return? A) small B) big C) 3 D) 5 β†’ A
  14. Which is NOT a comparison operator? A) > B) < C) = D) + β†’ D
  15. What does else do in cond? A) catches other cases B) ends program C) starts loop D) adds numbers β†’ A

πŸ”— Matching

TermMatch
1. #tA. false
2. #fB. true
3. condC. many choices
4. ifD. two choices

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

πŸ“ Short Answer

  1. Explain the difference between AND and OR.
  2. Why do we need logic in programming?
  3. Write a cond statement that tells if a number is positive, negative, or zero.

πŸ“– Scenario-based Exercises

Scenario: You are building a smart trash can that opens when a person approaches, but only if it's not raining. How would you write the logic?

Answer: (if (and person-approaches (not raining)) "open" "stay closed")

πŸ‘₯ Group Activity

Each group writes a "fortune teller" program. It asks for your age and gives a fortune: if under 10, "you will be a pilot"; if 10-15, "you will be a scientist"; else, "you will be a leader". Use cond.

πŸ§‘β€πŸ’» Individual Activity

Write a function called can-vote? that takes age and returns #t if age β‰₯ 18, else #f.

πŸ’¬ Classroom Discussion Questions

  • Can you think of a decision that requires AND? OR? NOT?
  • Why is it important to test both true and false cases?
  • How does logic help AI make smarter choices?

πŸ› οΈ Mini Project

Create a "traffic light" program. Use cond with a color input: "red" β†’ stop, "yellow" β†’ wait, "green" β†’ go, else β†’ "invalid".

πŸ“‹ Practical Assignment

Write a program that takes a student's score and outputs: "Excellent" for 90+, "Good" for 70-89, "OK" for 50-69, and "Needs Improvement" for below 50.

πŸ† Challenge Exercise

Write a function that takes three numbers and returns the largest. Use cond and comparisons.

πŸ”‘ Quiz Answers

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

🎁 Key Takeaways

  • Logic is the brain of AI.
  • True/false drives every decision.
  • if, cond, and, or, not are your logic tools.
  • Practice building small decision programs.
  • You are now ready for more complex AI!

πŸš€ Preparation for the Next Module

In Module Three, we will learn about repetition – how to make the computer repeat actions using loops and recursion. We'll build programs that can handle lots of data and do tasks over and over. Practice your logic skills, and get ready to make your programs even more powerful!


πŸŽ‰ You've completed Module Two Β· Keep up the great work, young AI specialist! πŸŽ‰

4

Module Three

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! πŸŽ‰

5

Module Four

Module 4 Β· Racket AI Specialist – Data Structures

πŸ—‚οΈ Module Four Β· Data Structures – Organising Information

Certified Racket AI Specialist Β· Building Smart Containers

πŸ“– Module Introduction

Hello, young organiser! πŸ‘‹ In Module Three, we learned to repeat tasks and process lists. But real-world data is often more complex than a simple list. We need better ways to organise information.

Think about a school. You don't just have a list of students β€” you also have their names, ages, classes, and scores. You need to keep all that related information together. That's where data structures come in.

In this module, we will learn about structures (custom containers for related data), association lists (key-value pairs), and trees (hierarchical data). These tools will help you build smarter, more realistic AI systems.

πŸ“¦ Fun fact: Data structures are like different types of boxes β€” some are good for storing books, others for storing toys. Choosing the right box makes everything easier!

🎯 Learning Objectives

After this module, you will be able to:

  • βœ”οΈ Understand why we need different data structures.
  • βœ”οΈ Create your own structures using struct.
  • βœ”οΈ Use association lists to store key-value pairs.
  • βœ”οΈ Build simple trees to represent hierarchical data.
  • βœ”οΈ Access and update data inside structures and lists.
  • βœ”οΈ Choose the right data structure for the job.
  • βœ”οΈ Build a small AI system that uses multiple structures.

πŸ“š Warm-up Story Β· The Great Library

Imagine you are in charge of a huge library. You have thousands of books. If you just pile them up, nobody can find anything. But if you organise them by category, author, and title, everything becomes easy to find.

In programming, data structures are like your library organisation system. They help you store, find, and use information quickly and correctly.

Today, we will build our own "organisers" β€” structures to hold related information, dictionaries to look things up, and trees to show relationships. Let's get organised!

   Without structure:
   [book1, book2, book3, ...]  (confusing)

   With structure:
   [ (title "Racket" author "Smith" year 2020),
     (title "AI" author "Jones" year 2021) ]
   (clear and organised)
  

🧩 Main Lessons

Lesson 1 Β· Why Data Structures Matter

Definition: A data structure is a way to store and organise data so that we can use it easily.

Why important: AI systems handle lots of data. Good structures make AI faster and easier to build.

Simple explanation: Think of a drawer. If you throw everything in, it's messy. If you use dividers, you can find things quickly. Data structures are like dividers.

Real-life: A phone book organises names and numbers.

School: A timetable organises subjects by day and time.

Home: A recipe book organises dishes by type (soup, rice, etc.).

Nigerian: A market seller organises goods by type: yams here, tomatoes there.

Illustration:

   Without structure:   [2, "Ade", #t, 5.6, "hello"]
   With structure:      (person name "Ade" age 12)
  
πŸ“Œ Mini summary: Data structures organise information so it's easy to understand and use.

Lesson 2 Β· Structures – Custom Containers

Definition: A structure (struct) is a custom data type that groups related pieces of information together.

Why important: Structures let you create your own data types, like "Student" or "Book", with named fields.

Simple explanation: It's like a form you fill out: name, age, class. Each person gets their own form.

Real-life: A passport contains name, photo, nationality.

School: A report card contains subject, score, grade.

Home: A gift card contains sender, receiver, amount.

Nigerian: A voter's card contains name, age, polling unit.

Illustration:

   (struct student (name age class))
   (define s1 (student "Ade" 12 "JSS2"))
   (student-name s1) β†’ "Ade"
   (student-age s1)  β†’ 12
  
πŸ“Œ Mini summary: struct creates a new type with named fields. Access fields with functions.

Lesson 3 Β· Creating and Using Structures

Let's create a structure for a book: title, author, pages.

   (struct book (title author pages))
   (define b1 (book "Racket for AI" "Dr. Ada" 120))
   (book-title b1)  β†’ "Racket for AI"
   (book-author b1) β†’ "Dr. Ada"
   (book-pages b1)  β†’ 120
  

You can also make lists of structures.

πŸ“Œ Mini summary: Define a structure, then create instances using the constructor (book ...).

Lesson 4 Β· Association Lists – Lookup Tables

Definition: An association list (alist) is a list of pairs: (key . value). It acts like a dictionary or lookup table.

Why important: AI often needs to look up values by key β€” like finding a word in a dictionary.

Simple explanation: It's like a label on a box: the label (key) tells you what's inside (value).

Real-life: A dictionary: word β†’ meaning.

School: A class list: name β†’ score.

Home: A chore chart: chore β†’ who does it.

Nigerian: A menu: food β†’ price.

Illustration:

   (define phone-list '((Ade . 080123) (Bola . 080456)))
   (assoc 'Ade phone-list) β†’ '(Ade . 080123)
   (cdr (assoc 'Ade phone-list)) β†’ 080123
  
πŸ“Œ Mini summary: Association lists map keys to values. Use assoc to find a key.

Lesson 5 Β· Working with Association Lists

We can add, find, and update values in alists. Racket provides functions like assoc and alist-update.

πŸ“Œ Mini summary: Association lists are simple and fast for small lookups.

Lesson 6 Β· Trees – Hierarchical Data

Definition: A tree is a data structure that has a root and branches. Each branch can have more branches. It's used for hierarchical data.

Why important: Many things are hierarchical: family trees, file systems, decision trees in AI.

Simple explanation: It's like a family tree: grandparents at the top, parents below, children below them.

Real-life: A company organisation chart: CEO β†’ managers β†’ employees.

School: A school system: Principal β†’ Head teachers β†’ Class teachers β†’ Students.

Home: A wardrobe: clothes β†’ tops β†’ shirts.

Nigerian: Traditional title system: Oba β†’ chiefs β†’ villagers.

Illustration:

         Root
        /    \
     NodeA   NodeB
     /  \      |
   Leaf1 Leaf2 Leaf3
  
πŸ“Œ Mini summary: Trees represent parent-child relationships.

Lesson 7 Β· Building a Simple Tree in Racket

We can represent a tree using lists: (value children...). For example: (1 (2 (4) (5)) (3 (6)))

   (define tree '(1 (2 (4) (5)) (3 (6))))
   ; tree with root 1, children 2 and 3, etc.
  

We can write functions to traverse trees.

πŸ“Œ Mini summary: Lists can represent trees. We can process them recursively.

Lesson 8 Β· Using Structures for Tree Nodes

Better: use structures to make trees clearer.

   (struct node (value left right))
   (define tree (node 5 (node 3 #f #f) (node 7 #f #f)))
  

This is a binary tree: each node has a value, left child, and right child.

πŸ“Œ Mini summary: Structures make tree nodes easy to understand.

Lesson 9 Β· Traversing a Tree

We can visit every node in a tree (called traversal). There are different orders: pre-order, in-order, post-order.

   (define (in-order tree)
     (if (empty? tree)
         '()
         (append (in-order (node-left tree))
                 (list (node-value tree))
                 (in-order (node-right tree)))))
  
πŸ“Œ Mini summary: Traversal means visiting each node in a specific order.

Lesson 10 Β· When to Use Each Structure

StructureUse whenExample
ListSimple ordered datascores of a game
StructRelated fieldsstudent record
Association listLookup by keydictionary
TreeHierarchical datafamily tree
πŸ“Œ Mini summary: Choose the structure that fits your data and what you want to do.

Lesson 11 Β· Building a Small AI System – Library Manager

Let's build a system that manages books using structures and association lists.

   (struct book (title author year))
   (define library '())
   (define (add-book library b) (cons b library))
   (define (find-by-author library author)
     (filter (lambda (b) (equal? (book-author b) author)) library))
  

This is a simple AI for managing a library!

πŸ“Œ Mini summary: We combined structures and lists to build a useful system.

Lesson 12 Β· Putting It All Together – A Student Database

Create a student structure with name, age, and scores. Store them in a list. Write functions to find students by name and to calculate average score.

πŸ“Œ Mini summary: We built a complete mini database β€” a foundation for AI systems.

πŸ“– Key Vocabulary

  • Data structure: A way to organise data.
  • Struct: A custom container for related fields.
  • Association list (alist): A list of (key . value) pairs.
  • Tree: A hierarchical structure with root and branches.
  • Node: An element in a tree.
  • Traversal: Visiting every node in a tree.
  • Key-value pair: A key that maps to a value.

🧠 Important Concepts

  • Organisation: Good structures make programs easier to write and understand.
  • Access: Each structure provides ways to get and set data.
  • Hierarchy: Trees show parent-child relationships.
  • Composition: Structures can contain other structures.

πŸ“˜ Step-by-Step Explanations

How to create a structure and use it:

  1. Define the structure: (struct person (name age))
  2. Create an instance: (define p (person "Ada" 12))
  3. Access fields: (person-name p) β†’ "Ada"
  4. Use in lists: (list (person "Bob" 10) (person "Eve" 11))

🌍 Real-life Examples

  • Online store: structures for products (name, price, stock).
  • Social media: structures for users (name, posts, friends).
  • Bank: structures for accounts (owner, balance, transactions).

πŸ‡³πŸ‡¬ Nigerian Examples

  • Market inventory: alist for item β†’ price.
  • School system: structures for students and teachers.
  • Village hierarchy: tree for traditional rulers.

🎈 Fun Examples

  • Struct for a video game character (name, health, power).
  • Alist for pet names β†’ animal type.
  • Tree for a story: beginning β†’ middle β†’ end.

🏠 Everyday Examples

  • Contacts: alist with name β†’ phone number.
  • Recipe: struct for ingredients and steps.
  • To-do list: list of tasks with priorities.

πŸ§‘β€πŸ« Teacher Notes

Use physical objects: folders for structs, sticky notes for alists, family trees for trees. Encourage students to think about organising their own belongings. Relate every structure to something tangible.

πŸ‘ͺ Parent Tips

Ask your child to describe how they organise their room. Relate that to data structures. Encourage them to think about how a library or shop organises items. Practice creating structures for things at home.

🌟 Interesting Facts

  • The first data structures were developed in the 1950s.
  • AI uses trees for decision-making (decision trees).
  • Google uses huge trees to organise web pages.

πŸ€” Did You Know?

Racket's struct can automatically generate functions for you: a constructor, field accessors, and even a predicate (like student?).

🧾 Remember This

  • Structures group related data.
  • Association lists map keys to values.
  • Trees show hierarchical relationships.
  • Choose the right structure for your data.

⚠️ Common Mistakes

  • Forgetting to use struct before creating an instance.
  • Using assoc on an alist with improper formatting.
  • Confusing tree nodes with lists.
  • Not handling empty trees in recursive functions.

βœ… Best Practices

  • Name structures clearly: student, book, etc.
  • Use empty? to check for empty lists and trees.
  • Write helper functions to access nested data.
  • Document what each field means.

πŸ“Š ASCII Illustrations

   Structure example:
   +------------------------+
   | Student                |
   +------------------------+
   | name: "Ade"            |
   | age: 12                |
   | class: "JSS2"          |
   +------------------------+
  
   Tree example:
         +-----+
         | 10  |  (root)
         +-----+
        /       \
     +---+     +---+
     | 5 |     | 15 |
     +---+     +---+
    /     \         \
  +---+   +---+     +---+
  | 2 |   | 7 |     | 20 |
  +---+   +---+     +---+
  

πŸ“‹ Comparison Table

StructureUseAccess
Listordered itemsfirst, rest
Structnamed fieldsfield functions
Alistlookupassoc
Treehierarchyrecursive traversal

πŸ“Œ End-of-Module Summary

You've learned how to organise data like a pro! You can now create structures, use association lists, and build trees. These tools are essential for any AI system β€” they help you store, find, and manage information efficiently. You're building the foundation for intelligent data handling.

❓ Frequently Asked Questions (10)

  1. What is a data structure? β€” A way to organise data.
  2. Why use struct? β€” To group related fields.
  3. What is an alist? β€” A list of key-value pairs.
  4. What is a tree? β€” A hierarchical structure.
  5. How do I access a struct field? β€” Use the field accessor.
  6. How do I find a key in an alist? β€” Use assoc.
  7. How do I traverse a tree? β€” Recursively visit left and right.
  8. Can I put a struct inside another struct? β€” Yes, you can nest them.
  9. Are alists fast? β€” They are fast for small data.
  10. Why are trees important for AI? β€” AI uses decision trees and hierarchical data.

πŸ“ Review Questions (15)

  1. What is a data structure?
  2. How do you define a struct in Racket?
  3. How do you create an instance of a struct?
  4. What is an association list?
  5. How do you look up a key in an alist?
  6. What is a tree?
  7. How do you represent a binary tree?
  8. What is tree traversal?
  9. Write a struct for a "car" with make, model, year.
  10. Write an alist for a menu (food β†’ price).
  11. How do you check if an alist has a key?
  12. What is a node in a tree?
  13. Why is hierarchy useful?
  14. Can a tree have more than two children?
  15. Give an example of a tree in real life.

✏️ Fill-in-the-Blank

  1. A ______ groups related fields together.
  2. An association list stores ______ pairs.
  3. A ______ has a root and branches.
  4. We use ______ to find a key in an alist.
  5. ______ traversal visits every node in a tree.

βœ… True or False

  1. Structures can have any number of fields. (True)
  2. Association lists can only store numbers. (False)
  3. A tree can have only two children. (False β€” it can have many.)
  4. You can nest a struct inside another struct. (True)
  5. Alists are used for hierarchical data. (False β€” trees are.)

πŸ”˜ Multiple Choice (15)

  1. Which groups related fields? A) struct B) alist C) tree D) list β†’ A
  2. Which is a key-value pair list? A) alist B) struct C) tree D) list β†’ A
  3. Which has a root and branches? A) tree B) struct C) alist D) list β†’ A
  4. How do you access a struct field? A) field function B) assoc C) first D) rest β†’ A
  5. How do you find a key in an alist? A) assoc B) struct C) tree D) list β†’ A
  6. What is a node? A) element in a tree B) field in struct C) key in alist D) item in list β†’ A
  7. Which is best for a dictionary? A) alist B) struct C) tree D) list β†’ A
  8. Which is best for a student record? A) struct B) alist C) tree D) list β†’ A
  9. Which is best for a family tree? A) tree B) struct C) alist D) list β†’ A
  10. Can a tree have no children? A) yes (leaf) B) no C) only one D) always two β†’ A
  11. What does (assoc 'a '((a . 1) (b . 2))) return? A) '(a . 1) B) 1 C) #f D) error β†’ A
  12. What does (struct person (name age)) create? A) a struct type B) a list C) a tree D) an alist β†’ A
  13. How do you create a person? A) (person "Ade" 12) B) (make-person) C) (struct person) D) (list "Ade" 12) β†’ A
  14. What is a leaf in a tree? A) a node with no children B) a node with many children C) the root D) a branch β†’ A
  15. Why use data structures? A) to organise data B) to slow down programs C) to delete data D) to confuse programmers β†’ A

πŸ”— Matching

TermMatch
1. structA. key-value pairs
2. alistB. hierarchical data
3. treeC. custom fields

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

πŸ“ Short Answer

  1. Explain the difference between a struct and an alist.
  2. Why are trees useful for AI?
  3. Write a struct for a "movie" with title, director, year.

πŸ“– Scenario-based Exercises

Scenario: You are building a school management system. You need to store student details (name, age, class) and also a list of their subjects and scores. How would you organise this using data structures?

Answer: Use a struct for student, and inside it, use an alist or another struct for subjects and scores.

πŸ‘₯ Group Activity

Each group designs a data structure for a "shop inventory" β€” products with name, price, and quantity. They also create an alist for discounts. Present the design.

πŸ§‘β€πŸ’» Individual Activity

Write a struct for a "phone" with brand, model, and price. Create a list of three phones and write a function to find the most expensive phone.

πŸ’¬ Classroom Discussion Questions

  • What data structure would you use for a dictionary?
  • How is a tree like a school system?
  • Why is it important to choose the right structure?

πŸ› οΈ Mini Project

Build a "library manager" that stores books (title, author, year) and allows you to add, list, and find books by author.

πŸ“‹ Practical Assignment

Create a student database using structs. Write functions to add a student, find a student by name, and calculate the average age of all students.

πŸ† Challenge Exercise

Write a function that takes a binary tree and returns the sum of all values. (Assume each node has a value and left/right children.)

πŸ”‘ Quiz Answers

Multiple choice answers: 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

  • Data structures organise information.
  • Structs group related fields.
  • Alists provide key-value lookup.
  • Trees show hierarchy.
  • Choose the right structure for your problem.

πŸš€ Preparation for the Next Module

In Module Five, we will dive into recursion on trees and more advanced data processing. You'll learn to manipulate trees, build decision trees for AI, and combine structures with recursion. Keep practising with structures and lists β€” they will be your main tools!


πŸŽ‰ You've completed Module Four Β· You are now a data structure master! πŸŽ‰

6

Module Five

Module 5 Β· Racket AI Specialist – Recursion & Trees

🌳 Module Five · Recursion on Trees & Advanced Data Processing

Certified Racket AI Specialist Β· Mastering Hierarchies

πŸ“– Module Introduction

Hello, clever thinker! πŸ‘‹ In Module Four, we learned about data structures like structs, association lists, and trees. Now we will become masters of trees β€” one of the most important structures in AI.

Think about how your family tree works: you start with your grandparents, then parents, then you, then your siblings. A computer can use this same idea to make decisions, organise data, and even play games!

In this module, we will learn how to walk through (traverse) trees, search for values in trees, and even build decision trees β€” the same kind used in real AI systems to decide things like whether to give you a loan or diagnose an illness. By the end, you'll be able to build your own simple AI that makes decisions based on a tree!

🌲 Fun fact: Decision trees are used in many real-world AI systems β€” from healthcare to video games!

🎯 Learning Objectives

After this module, you will be able to:

  • βœ”οΈ Understand what a tree is and why it's important for AI.
  • βœ”οΈ Traverse a tree in different ways (pre-order, in-order, post-order).
  • βœ”οΈ Search for a value in a tree.
  • βœ”οΈ Build a decision tree for a simple AI.
  • βœ”οΈ Use recursion to process tree data.
  • βœ”οΈ Combine trees with structures for more complex data.
  • βœ”οΈ Understand how AI uses trees for decision-making.

πŸ“š Warm-up Story Β· The Magical Maze

Imagine you are in a magical maze. At each junction, you can go left or right. Some paths lead to treasure, others lead to dead ends. You want to find all the treasure.

If you start at the entrance and explore every path, you are traversing the maze. You might decide to go left first, then right β€” that's an order of traversal.

In programming, a tree is like that maze. Each node (junction) has branches (paths). We can write recursive functions to explore every node and find what we need.

Let's learn how to navigate these magical trees!

   Magical Maze (Tree):
        Entrance
        /      \
      Left     Right
      /  \      /  \
    L1   L2   R1   R2
  

🧩 Main Lessons

Lesson 1 Β· Review: What is a Tree?

Definition: A tree is a structure with a root (top) and branches (children). Each branch can have more branches. A node with no children is called a leaf.

Why important: Trees are everywhere in AI: decision trees, file systems, website menus, and more.

Simple explanation: Think of a family tree: grandparents at the top, then parents, then children. That's a tree.

Real-life: A company organogram: CEO β†’ managers β†’ employees.

School: A school system: Principal β†’ Head Teachers β†’ Class Teachers β†’ Students.

Home: A wardrobe: Clothes β†’ Tops β†’ Shirts.

Nigerian: Traditional title system: Oba β†’ Chiefs β†’ Village Heads β†’ People.

Illustration:

         Root
        /    \
     NodeA   NodeB
     /  \      |
   Leaf1 Leaf2 Leaf3
  
πŸ“Œ Mini summary: A tree is a hierarchy with a root and branches.

Lesson 2 Β· Representing Trees in Racket

We can use structures to represent tree nodes. Each node has a value and a list of children.

   (struct node (value children))
   (define leaf1 (node 5 '()))
   (define leaf2 (node 7 '()))
   (define branch (node 3 (list leaf1 leaf2)))
   (define root (node 10 (list branch)))
  

This creates a tree: root 10 β†’ child 3 β†’ children 5 and 7.

πŸ“Œ Mini summary: We use structs to build trees with a value and children list.

Lesson 3 Β· Pre-order Traversal

Definition: Pre-order traversal visits the current node first, then each child.

Why important: Useful for copying a tree or saving its structure.

Simple explanation: Like a teacher calling out the class list: "Ade, then his children, then Bola..."

Real-life: Reading a book: start at chapter 1, then its sections.

School: Taking attendance: call the class captain, then their group members.

Home: Packing a suitcase: put big items first, then smaller ones.

Nigerian: Serving food: give the head of the family first, then others.

Illustration:

   Pre-order: Root β†’ Left β†’ Right
   Tree:      10
            /    \
           5      3
          / \    / \
         2   7  4   6
   Pre-order: 10, 5, 2, 7, 3, 4, 6
  
   (define (pre-order tree)
     (if (empty? (node-children tree))
         (list (node-value tree))
         (cons (node-value tree)
               (foldr append '() (map pre-order (node-children tree))))))
  
πŸ“Œ Mini summary: Pre-order: visit node, then children.

Lesson 4 Β· Post-order Traversal

Definition: Post-order visits all children first, then the node itself.

Why important: Used to calculate totals or evaluate expressions.

Simple explanation: Like cleaning a room: you clean the floor, then the table, then you leave.

Real-life: Eating a meal: you eat the vegetables, then the meat, then you finish.

School: Grading: you mark each student's work, then calculate the class average.

Home: Taking out trash: you empty all bins, then take the bag out.

Nigerian: Harvesting: you pick all the fruits, then take them to the market.

Illustration:

   Post-order: Left β†’ Right β†’ Root
   Tree:      10
            /    \
           5      3
          / \    / \
         2   7  4   6
   Post-order: 2, 7, 5, 4, 6, 3, 10
  
   (define (post-order tree)
     (if (empty? (node-children tree))
         (list (node-value tree))
         (append (foldr append '() (map post-order (node-children tree)))
                 (list (node-value tree)))))
  
πŸ“Œ Mini summary: Post-order: visit children, then node.

Lesson 5 Β· In-order Traversal (for binary trees)

Definition: In-order visits left child, then node, then right child (for binary trees).

Why important: This is used for sorted data β€” like printing a sorted list.

Simple explanation: Like reading a dictionary: A, then B, then C...

Real-life: Organising files by date: oldest first, then newest.

School: Calling roll: start from A, go to Z.

Home: Sorting toys: put all red ones, then blue, then green.

Nigerian: Market prices: low to high.

Illustration:

   In-order: Left β†’ Root β†’ Right
   Tree:      10
            /    \
           5      3
          / \    / \
         2   7  4   6
   In-order: 2, 5, 7, 10, 4, 3, 6
  
πŸ“Œ Mini summary: In-order: left, node, right (for binary trees).

Lesson 6 Β· Searching in a Tree

We can search for a value in a tree by traversing it and checking each node.

   (define (search tree target)
     (cond
       [(equal? (node-value tree) target) #t]
       [(empty? (node-children tree)) #f]
       [else (ormap (lambda (child) (search child target)) (node-children tree))]))
  
πŸ“Œ Mini summary: Search uses recursion to check every node.

Lesson 7 Β· Counting Nodes

We can count how many nodes are in a tree by traversing it.

   (define (count-nodes tree)
     (if (empty? (node-children tree))
         1
         (+ 1 (foldl + 0 (map count-nodes (node-children tree))))))
  
πŸ“Œ Mini summary: Count all nodes by recursion.

Lesson 8 Β· Height of a Tree

The height of a tree is the longest path from root to a leaf.

   (define (height tree)
     (if (empty? (node-children tree))
         1
         (+ 1 (apply max (map height (node-children tree))))))
  
πŸ“Œ Mini summary: Height is the longest branch length.

Lesson 9 Β· Building a Decision Tree

A decision tree is a tree where each node asks a question, and the branches are the answers. At the leaves, we get a decision.

Example: Should I play outside?

   Decision Tree:
   Is it sunny?
      /      \
    Yes      No
    /          \
   Is it warm?  Stay inside
    /    \
   Yes    No
   /        \
Play      Stay in
  

We can build this in Racket using structs.

πŸ“Œ Mini summary: Decision trees ask questions to reach a decision.

Lesson 10 Β· Implementing a Decision Tree

Let's implement a simple decision tree that decides what to wear.

   (struct question (text yes no))
   (struct answer (text))
   (define decision-tree
     (question "Is it raining?"
       (question "Is it windy?"
         (answer "Wear a jacket and umbrella")
         (answer "Wear a jacket"))
       (answer "Wear light clothes")))
  

We can write a function to evaluate the tree with user input.

πŸ“Œ Mini summary: We can implement decision trees with structures.

Lesson 11 Β· Evaluating a Decision Tree

Write a function that asks questions and returns the final answer.

   (define (decide tree)
     (cond
       [(answer? tree) (answer-text tree)]
       [(question? tree)
        (display (question-text tree))
        (newline)
        (if (equal? (read-line) "yes")
            (decide (question-yes tree))
            (decide (question-no tree)))]))
  

This creates an interactive AI!

πŸ“Œ Mini summary: Evaluating a decision tree asks questions and follows the path.

Lesson 12 Β· Putting It All Together – A Smart Chatbot

Let's build a simple chatbot that helps decide what to eat for lunch.

   ; Build the tree
   (define food-tree
     (question "Do you want something hot?"
       (question "Do you want rice?"
         (answer "Jollof rice")
         (answer "Yam and egg"))
       (question "Do you want something cold?"
         (answer "Salad")
         (answer "Fruit juice"))))
   ; Run (decide food-tree)
  

You just built a tiny AI assistant!

πŸ“Œ Mini summary: We combined everything to build an AI chatbot.

πŸ“– Key Vocabulary

  • Tree: A structure with a root and branches.
  • Node: An element in a tree.
  • Leaf: A node with no children.
  • Traversal: Visiting every node in a tree.
  • Pre-order: Node, then children.
  • Post-order: Children, then node.
  • In-order: Left, node, right.
  • Decision tree: A tree used for making decisions.

🧠 Important Concepts

  • Recursion is key: Trees are processed recursively.
  • Order matters: Different traversals give different results.
  • Decision trees are AI: They are used in many AI systems.
  • Composition: Trees can be combined with structs.

πŸ“˜ Step-by-Step Explanations

How to traverse a tree:

  1. Define the tree using structs or lists.
  2. Write a recursive function that handles a node.
  3. For pre-order: process node, then process each child.
  4. For post-order: process each child, then process node.
  5. For in-order (binary): process left, node, right.

🌍 Real-life Examples

  • Decision trees in medicine: diagnose illness.
  • Decision trees in banking: approve loans.
  • File systems: folders and subfolders.

πŸ‡³πŸ‡¬ Nigerian Examples

  • Market decisions: which market to go to based on price and distance.
  • School placement: which class a student should be in.
  • Village governance: decision tree for conflict resolution.

🎈 Fun Examples

  • What game to play: based on number of players.
  • What to watch: based on mood.
  • Which pet to get: based on house size.

🏠 Everyday Examples

  • What to wear: based on weather.
  • What to eat: based on hunger.
  • Which route to take: based on traffic.

πŸ§‘β€πŸ« Teacher Notes

Use physical trees (draw on board). Use real decision-making scenarios. Encourage students to build decision trees for everyday choices. Emphasise that recursion is natural for trees.

πŸ‘ͺ Parent Tips

Ask your child to draw a decision tree for a simple decision (like what to wear). Discuss how computers use these trees. Practice together by building a tree for a family decision.

🌟 Interesting Facts

  • Decision trees are used in Google's search algorithm.
  • The first decision tree was developed in the 1960s.
  • AI can learn decision trees automatically from data.

πŸ€” Did You Know?

Decision trees are so popular because they are easy to understand. You can draw them on a piece of paper and explain them to anyone!

🧾 Remember This

  • Trees have a root and branches.
  • Traversal visits every node.
  • Pre-order: node first.
  • Post-order: node last.
  • Decision trees help AI make decisions.

⚠️ Common Mistakes

  • Forgetting the base case in recursive traversal.
  • Not handling empty children lists.
  • Confusing pre-order and post-order.
  • Not using empty? to check for no children.

βœ… Best Practices

  • Use structs to represent tree nodes.
  • Always write the base case first.
  • Use map and fold for child processing.
  • Test with small trees first.

πŸ“Š ASCII Illustrations

   Tree traversal order:
   Pre-order:  Root β†’ Left β†’ Right
   In-order:   Left β†’ Root β†’ Right
   Post-order: Left β†’ Right β†’ Root
  
   Decision tree flow:
   Start
     |
     V
   Question 1
     /     \
   Yes      No
    |        |
    V        V
   Q2       Q3
    |         |
    V         V
   Decision  Decision
  

πŸ“‹ Comparison Table

TraversalOrderUse
Pre-orderNode, childrenCopying trees
Post-orderChildren, nodeCalculating totals
In-orderLeft, node, rightSorted output

πŸ“Œ End-of-Module Summary

You've become a tree master! You can now traverse trees in different orders, search for values, count nodes, and even build decision trees β€” the heart of many AI systems. You've built a simple chatbot that makes decisions. These skills are directly used in real AI applications. You're now ready to explore even more advanced AI topics!

❓ Frequently Asked Questions (10)

  1. What is a tree? β€” A structure with a root and branches.
  2. What is a leaf? β€” A node with no children.
  3. What is pre-order traversal? β€” Visit node first, then children.
  4. What is post-order traversal? β€” Visit children first, then node.
  5. What is a decision tree? β€” A tree that helps make decisions.
  6. How do you search a tree? β€” Traverse it and check each node.
  7. What is the height of a tree? β€” The longest path from root to leaf.
  8. Why are trees important for AI? β€” They are used for decision-making.
  9. Can a tree have more than two children? β€” Yes, a general tree can.
  10. What is a binary tree? β€” A tree where each node has at most two children.

πŸ“ Review Questions (15)

  1. What is a tree?
  2. What is a leaf in a tree?
  3. What is pre-order traversal?
  4. What is post-order traversal?
  5. What is in-order traversal?
  6. How do you search for a value in a tree?
  7. What is a decision tree?
  8. Write a function to count the nodes in a tree.
  9. Write a function to calculate the height of a tree.
  10. How do you represent a tree in Racket?
  11. What is the difference between pre-order and post-order?
  12. Why is recursion useful for trees?
  13. Give an example of a decision tree in real life.
  14. Can a tree have zero nodes?
  15. What is the root of a tree?

✏️ Fill-in-the-Blank

  1. A ______ has a root and branches.
  2. A node with no children is called a ______.
  3. ______ traversal visits the node first, then children.
  4. ______ traversal visits children first, then node.
  5. A ______ tree helps make decisions.

βœ… True or False

  1. Pre-order visits children first. (False)
  2. Post-order visits node last. (True)
  3. A leaf has no children. (True)
  4. In-order is only for binary trees. (True)
  5. Decision trees are not used in AI. (False)

πŸ”˜ Multiple Choice (15)

  1. What is a tree? A) root + branches B) list C) alist D) struct β†’ A
  2. What is a leaf? A) node with no children B) root C) child D) branch β†’ A
  3. Pre-order visits in what order? A) node, children B) children, node C) left, node, right D) right, node, left β†’ A
  4. Post-order visits in what order? A) children, node B) node, children C) left, node, right D) right, node, left β†’ A
  5. In-order visits in what order (for binary)? A) left, node, right B) node, left, right C) right, node, left D) children, node β†’ A
  6. What is a decision tree? A) helps make decisions B) stores numbers C) sorts lists D) counts nodes β†’ A
  7. How do you search a tree? A) traverse it B) use assoc C) use map D) use filter β†’ A
  8. What is the height of a tree? A) longest path B) number of nodes C) number of leaves D) root value β†’ A
  9. What is recursion? A) function calls itself B) loop C) if statement D) struct β†’ A
  10. Can a tree have more than two children? A) yes B) no C) only two D) only one β†’ A
  11. What is a binary tree? A) at most two children B) exactly two children C) only leaves D) no root β†’ A
  12. Which traversal is used for copying trees? A) pre-order B) post-order C) in-order D) random β†’ A
  13. Which traversal is used for evaluating expressions? A) post-order B) pre-order C) in-order D) none β†’ A
  14. What does (node-value tree) return? A) the value of the node B) the children C) the root D) the leaf β†’ A
  15. Why are trees important? A) organise data B) slow down programs C) delete data D) confuse programmers β†’ A

πŸ”— Matching

TermMatch
1. Pre-orderA. children first
2. Post-orderB. node first
3. LeafC. no children

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

πŸ“ Short Answer

  1. Explain the difference between pre-order and post-order.
  2. What is a decision tree and why is it useful?
  3. Write a function that returns the sum of all values in a tree.

πŸ“– Scenario-based Exercises

Scenario: You are building a system to recommend a movie based on age and interest. Design a decision tree for this.

Answer: Tree: Is age < 12? β†’ Cartoon; else β†’ Is it action? β†’ Action; else β†’ Comedy.

πŸ‘₯ Group Activity

Each group designs a decision tree for choosing a vacation destination. Questions: budget, beach or mountains, etc.

πŸ§‘β€πŸ’» Individual Activity

Write a function that counts the number of leaves in a tree.

πŸ’¬ Classroom Discussion Questions

  • How is a decision tree like a flowchart?
  • Why are trees better than lists for some data?
  • What real-world problems can be solved with decision trees?

πŸ› οΈ Mini Project

Build a decision tree that helps choose a pet. Questions: Do you have a yard? Do you like walking? etc.

πŸ“‹ Practical Assignment

Implement a decision tree for a restaurant recommendation based on cuisine preference and budget.

πŸ† Challenge Exercise

Write a function that flattens a tree into a list using pre-order traversal.

πŸ”‘ Quiz Answers

Multiple choice answers: 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

  • Trees are hierarchical structures.
  • Traversal visits every node in a specific order.
  • Decision trees are a core AI tool.
  • Recursion is natural for trees.
  • You can build interactive AI with decision trees.

πŸš€ Preparation for the Next Module

In Module Six, we will explore Generative AI β€” how computers can create new things like stories, pictures, and music. We'll use what we've learned about trees and recursion to build creative programs. Get ready to become an AI artist!


πŸŽ‰ You've completed Module Five Β· You are now a tree and decision-making expert! πŸŽ‰

7

Module Six

Module 6 Β· Racket AI Specialist – Generative AI

✨ Module Six Β· Generative AI – Creating New Things

Certified Racket AI Specialist Β· The Creative Side of AI

πŸ“– Module Introduction

Hello, young creator! πŸ‘‹ So far, we've taught computers to do math, make decisions, and organise data. Now we will teach them something truly magical: how to create new things.

Think about a painter who mixes colours to make a new shade, or a musician who combines notes to make a new song. AI can do this too! We call this Generative AI β€” AI that creates new content like stories, poems, pictures, and even music.

In this module, we will learn the basics of how AI creates things. We'll use Racket to build our own simple generators β€” programs that produce new text, new lists, and even new structures. You'll become an AI artist!

🎨 Fun fact: Generative AI can now create paintings that sell for millions of dollars, and music that sounds like it was made by famous composers!

🎯 Learning Objectives

After this module, you will be able to:

  • βœ”οΈ Understand what Generative AI is and why it's exciting.
  • βœ”οΈ Use randomness to create unpredictable outputs.
  • βœ”οΈ Build a text generator that creates new sentences.
  • βœ”οΈ Build a pattern generator that creates art.
  • βœ”οΈ Use combinations to create new things from existing parts.
  • βœ”οΈ Understand how AI can "imagine" new things.
  • βœ”οΈ Build your own simple story generator.

πŸ“š Warm-up Story Β· The Magical Chef

Imagine you have a magical chef. Instead of following a recipe, this chef can invent new dishes. You give it some ingredients β€” rice, chicken, spices β€” and it creates a brand new meal that nobody has ever eaten before!

Generative AI works the same way. You give it examples (like words or pictures), and it learns the patterns. Then it uses those patterns to make something new.

Today, we'll build our own "magical chefs" using Racket. They won't be as smart as the ones in big companies, but they will create things that are new and fun!

   Ingredients (data)  β†’  AI learns patterns  β†’  Creates new things
      "cat", "dog", "bird"  β†’  "cog", "bat", "dird"  (new invented words!)
  

🧩 Main Lessons

Lesson 1 Β· What is Generative AI?

Definition: Generative AI is a type of AI that creates new content β€” like text, images, music, or code β€” instead of just analysing or classifying.

Why important: Generative AI is used to create art, write stories, help with design, and even discover new medicines!

Simple explanation: It's like a robot that can paint a new picture instead of just telling you about an existing one.

Real-life: ChatGPT writes new stories. DALL-E creates new images.

School: Imagine a computer that can write a new essay for you on any topic.

Home: A smart speaker that can make up a new bedtime story.

Nigerian: An AI that creates new African-inspired fashion designs.

Illustration:

   +-------------------+      +-------------------+
   |  Examples (data)  | ---> |  Generative AI    | --->  New creation
   +-------------------+      +-------------------+
         cats, dogs              "cog" (new animal)
         jazz, blues             new music style
  
πŸ“Œ Mini summary: Generative AI creates new things from patterns it learns.

Lesson 2 Β· Randomness – The Spark of Creativity

Definition: Randomness is when something happens by chance, without a fixed order.

Why important: AI uses randomness to create variety. Without randomness, everything would be the same.

Simple explanation: It's like rolling a dice. You never know what number you'll get.

Real-life: A lottery draw uses randomness.

School: A teacher randomly picking a student to answer a question.

Home: Picking a random movie to watch.

Nigerian: Using a lucky draw at a carnival.

Illustration:

   (define (roll-dice) (random 6))
   (roll-dice) β†’ 3
   (roll-dice) β†’ 5
   (roll-dice) β†’ 2
  
πŸ“Œ Mini summary: Randomness makes outputs unpredictable and creative.

Lesson 3 Β· Picking Random Items from a List

We can use random and list-ref to pick a random item from a list.

   (define fruits '("apple" "banana" "orange" "mango"))
   (define (pick-random lst) (list-ref lst (random (length lst))))
   (pick-random fruits) β†’ "banana"
  

This is the simplest generative technique!

πŸ“Œ Mini summary: We can pick random items to create new combinations.

Lesson 4 Β· Building a Simple Word Generator

We can combine random pieces to make new words.

   (define starters '("b" "c" "d" "f" "g"))
   (define middles '("a" "e" "i" "o" "u"))
   (define endings '("t" "n" "p" "m"))
   (define (new-word)
     (string-append (pick-random starters) (pick-random middles) (pick-random endings)))
   (new-word) β†’ "bim"
   (new-word) β†’ "gan"
  

We just created a word generator!

πŸ“Œ Mini summary: Randomly combining pieces creates new words.

Lesson 5 Β· Building a Story Generator

We can use the same idea to create simple stories.

   (define characters '("Ade" "Bola" "Chidi" "Dara"))
   (define actions '("ran" "jumped" "sang" "danced"))
   (define places '("market" "school" "beach" "village"))
   (define (story)
     (string-append (pick-random characters) " " (pick-random actions) " to the " (pick-random places)))
   (story) β†’ "Bola sang to the beach"
  
πŸ“Œ Mini summary: Combining random parts creates new stories.

Lesson 6 Β· Using Templates for Better Stories

We can use a template to make stories more interesting.

   (define templates
     '("The ~a loved to ~a in the ~a"
       "Every day, ~a would ~a at the ~a"
       "~a went to the ~a to ~a"))
   (define (better-story)
     (format (pick-random templates)
             (pick-random characters)
             (pick-random actions)
             (pick-random places)))
  
πŸ“Œ Mini summary: Templates make generated text more meaningful.

Lesson 7 Β· Creating Art with Text

We can generate simple ASCII art using random choices.

   (define shapes '("  *  " " *** " "*****"))
   (define (make-art)
     (string-join (list (pick-random shapes) (pick-random shapes) (pick-random shapes)) "\n"))
   (make-art)
   β†’   *
      ***
     *****
  
πŸ“Œ Mini summary: We can generate simple visual patterns.

Lesson 8 Β· Generative Lists

We can generate lists of random numbers or items.

   (define (random-list n)
     (if (= n 0)
         '()
         (cons (random 10) (random-list (- n 1)))))
   (random-list 5) β†’ '(3 7 1 8 4)
  
πŸ“Œ Mini summary: We can generate lists of any length with random values.

Lesson 9 Β· Generating Structured Data

We can generate structs with random fields.

   (struct person (name age))
   (define (random-person)
     (person (pick-random names) (+ 5 (random 15))))
   (random-person) β†’ (person "Ade" 12)
  
πŸ“Œ Mini summary: We can generate complex data structures.

Lesson 10 Β· Combining Patterns – The Power of Mixing

Generative AI works by learning patterns and mixing them. We can mix different categories.

   (define animals '("lion" "tiger" "bear"))
   (define colors '("red" "blue" "golden"))
   (define (new-animal) (string-append (pick-random colors) " " (pick-random animals)))
   (new-animal) β†’ "red tiger"
  
πŸ“Œ Mini summary: Mixing patterns creates novel combinations.

Lesson 11 Β· Building a Recipe Generator

We can generate new recipes by combining ingredients.

   (define meats '("chicken" "beef" "fish"))
   (define spices '("pepper" "ginger" "garlic"))
   (define veggies '("onions" "tomatoes" "peppers"))
   (define (recipe)
     (string-append "Cook " (pick-random meats) " with " (pick-random spices) " and " (pick-random veggies)))
  
πŸ“Œ Mini summary: We can generate creative recipes!

Lesson 12 Β· Putting It All Together – A Complete Generator

Let's build a program that generates a full story with a character, setting, and plot.

   (define (full-story)
     (string-append
       "Once upon a time, " (pick-random characters)
       " lived in " (pick-random places)
       ". One day, they " (pick-random actions)
       " and found a " (pick-random animals)
       ". They became friends!"))
   (full-story)
   β†’ "Once upon a time, Chidi lived in school. One day, they danced and found a tiger. They became friends!"
  

You just built a Generative AI system!

πŸ“Œ Mini summary: We combined all techniques to build a complete story generator.

πŸ“– Key Vocabulary

  • Generative AI: AI that creates new content.
  • Randomness: Something that happens by chance.
  • Template: A pattern with blanks to fill in.
  • Combination: Mixing different elements together.
  • Pattern: A repeated way of doing something.
  • Generator: A program that creates new things.

🧠 Important Concepts

  • Pattern recognition: AI learns patterns from examples.
  • Randomness: Adds variety and creativity.
  • Combination: New things come from mixing existing things.
  • Template filling: A common generative technique.

πŸ“˜ Step-by-Step Explanations

How to build a generator:

  1. Decide what you want to generate (words, stories, art).
  2. Gather examples and break them into pieces.
  3. Create lists of each type of piece.
  4. Write a function that randomly picks pieces and combines them.
  5. Test it many times to see the variety.
  6. Add templates to make the output better.

🌍 Real-life Examples

  • ChatGPT: generates text responses.
  • DALL-E: generates images from text.
  • Music AI: generates new songs.

πŸ‡³πŸ‡¬ Nigerian Examples

  • AI that generates new Ankara patterns.
  • AI that writes new Nigerian folktales.
  • AI that creates new recipes for Nigerian dishes.

🎈 Fun Examples

  • Generate new ice cream flavours.
  • Generate new superhero names.
  • Generate new holiday destinations.

🏠 Everyday Examples

  • Making a new sandwich from available ingredients.
  • Choosing a random outfit.
  • Inventing a new game with existing rules.

πŸ§‘β€πŸ« Teacher Notes

Encourage creativity. Let students build generators for anything they like. Emphasise that generative AI starts with simple techniques. Use the "mix and match" concept. Show how big AI uses these same ideas on a massive scale.

πŸ‘ͺ Parent Tips

Ask your child to generate stories for you. Use the generators to create fun family activities β€” like a new recipe for dinner or a new bedtime story. Celebrate the creativity!

🌟 Interesting Facts

  • Some AI-generated art has been sold for over $400,000.
  • Generative AI can create new drug molecules for medicine.
  • AI can generate new levels in video games.

πŸ€” Did You Know?

The first generative AI programs in the 1960s could generate simple poetry. Today, they can write entire novels!

🧾 Remember This

  • Generative AI creates new things.
  • Randomness is important for creativity.
  • We combine pieces to make new things.
  • Templates make outputs better.
  • You can build your own generators!

⚠️ Common Mistakes

  • Forgetting to use random for variety.
  • Using lists that are too small β€” not enough variety.
  • Not testing the generator enough times.
  • Making templates too strict β€” no creativity.

βœ… Best Practices

  • Use large lists for more variety.
  • Use templates for better structure.
  • Test your generator many times.
  • Combine different types of data.

πŸ“Š ASCII Illustrations

   Generator flow:
   Lists of pieces  β†’  Random pick  β†’  Combine  β†’  New creation

   Example:
   [Ade, Bola, Chidi] + [ran, sang] + [market, school]
   β†’ "Chidi sang at school"
  
   Tree of combinations:
       Start
         |
         V
    Choose character
         |
         V
    Choose action
         |
         V
    Choose place
         |
         V
    Combine all β†’ story!
  

πŸ“‹ Comparison Table

TechniqueHow it worksExample
Random pickPick random item(pick-random names)
CombinationMix multiple picks(string-append name action place)
TemplateFill in blanks"The ~a ~a in the ~a"

πŸ“Œ End-of-Module Summary

You've unlocked the creative side of AI! You learned about generative AI, used randomness, combined pieces to create new things, and built story generators and more. These are the same techniques used by big AI companies, just on a smaller scale. You are now an AI creator!

❓ Frequently Asked Questions (10)

  1. What is Generative AI? β€” AI that creates new content.
  2. Why use randomness? β€” To make outputs varied and creative.
  3. What is a template? β€” A pattern with blanks to fill.
  4. Can AI create art? β€” Yes, many AI systems create art.
  5. How do we combine pieces? β€” Using functions like string-append.
  6. What is a generator? β€” A program that creates new things.
  7. Can AI write stories? β€” Yes, some AI writes stories.
  8. Why is combination important? β€” New things come from mixing.
  9. How can I make my generator better? β€” Use more data and better templates.
  10. Is this really AI? β€” Yes, this is how many generative AI systems start!

πŸ“ Review Questions (15)

  1. What is Generative AI?
  2. Why do we use randomness?
  3. How do you pick a random item from a list?
  4. Write a function that picks a random word from a list.
  5. What is a template?
  6. How can you make a story generator?
  7. What is combination in generative AI?
  8. Write a function that generates a random sentence.
  9. How can you generate a random number?
  10. Why are templates useful?
  11. What is a generator?
  12. Give an example of a real generative AI.
  13. How can you generate a random list?
  14. What is the difference between random and fixed?
  15. How do you combine strings in Racket?

✏️ Fill-in-the-Blank

  1. ______ AI creates new content.
  2. ______ adds variety to generated content.
  3. A ______ is a pattern with blanks to fill.
  4. We use ______ to combine pieces.
  5. A ______ is a program that creates new things.

βœ… True or False

  1. Generative AI only analyses data. (False)
  2. Randomness is important for creativity. (True)
  3. Templates make outputs less interesting. (False)
  4. Combining pieces is a generative technique. (True)
  5. AI cannot generate new images. (False)

πŸ”˜ Multiple Choice (15)

  1. What is Generative AI? A) creates new content B) sorts data C) adds numbers D) deletes files β†’ A
  2. Why use randomness? A) for variety B) to slow down C) to delete data D) to sort β†’ A
  3. How do you pick a random item? A) list-ref + random B) first C) rest D) filter β†’ A
  4. What is a template? A) a pattern B) a list C) a number D) a string β†’ A
  5. What does (string-append "hi" " there") do? A) combines strings B) adds numbers C) sorts D) filters β†’ A
  6. What is a generator? A) creates new things B) deletes things C) sorts things D) counts things β†’ A
  7. Which is an example of generative AI? A) ChatGPT B) Calculator C) Database D) Spreadsheet β†’ A
  8. What does (pick-random lst) do? A) picks random item B) sorts list C) deletes list D) adds to list β†’ A
  9. How can we make a story generator? A) combine random parts B) only use one part C) no randomness D) use fixed text β†’ A
  10. What is combination? A) mixing things B) deleting things C) sorting things D) counting things β†’ A
  11. What does (random 10) return? A) number 0-9 B) 10 C) list D) string β†’ A
  12. Why are templates useful? A) make output structured B) add randomness C) delete data D) sort lists β†’ A
  13. Can AI generate music? A) yes B) no C) only if told D) never β†’ A
  14. What is the first step in building a generator? A) gather pieces B) delete data C) sort list D) add numbers β†’ A
  15. What does (length lst) do? A) returns length B) picks random C) sorts D) deletes β†’ A

πŸ”— Matching

TermMatch
1. GenerativeA. creates new things
2. RandomB. by chance
3. TemplateC. pattern with blanks

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

πŸ“ Short Answer

  1. Explain how randomness helps AI create new things.
  2. What is a template and why is it useful?
  3. Write a function that generates a random sentence with a subject, verb, and object.

πŸ“– Scenario-based Exercises

Scenario: You are building an AI that generates new superhero names. You have lists of adjectives (e.g., "mighty", "shadow") and nouns (e.g., "tiger", "dragon"). How would you build the generator?

Answer: Use random pick from adjectives and nouns, combine with string-append.

πŸ‘₯ Group Activity

Each group builds a generator for a topic of their choice (e.g., new ice cream flavours, new sports names, new holiday destinations). Share and compare outputs.

πŸ§‘β€πŸ’» Individual Activity

Build a generator that creates new pet names by combining syllables.

πŸ’¬ Classroom Discussion Questions

  • How is generative AI different from other AI?
  • Can a generator ever run out of new ideas?
  • How could you make your generator even more creative?

πŸ› οΈ Mini Project

Build a "magic spell" generator. Create lists of words that sound magical and combine them to create new spells with "powers".

πŸ“‹ Practical Assignment

Build a generator that creates new Nigerian dish descriptions. Use ingredients, cooking methods, and tasty words.

πŸ† Challenge Exercise

Build a generator that creates simple poems. Use rhyme patterns and random word selection.

πŸ”‘ Quiz Answers

Multiple choice answers: 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

  • Generative AI creates new, original content.
  • Randomness is essential for creativity.
  • Combining pieces leads to new things.
  • Templates improve the quality of generation.
  • You can build your own generative systems!

πŸš€ Preparation for the Next Module

In Module Seven, we'll explore Machine Learning β€” how computers can learn from examples instead of being told exactly what to do. We'll build a simple learning system that improves over time. Get ready to teach your computer!


πŸŽ‰ You've completed Module Six Β· You are now a Generative AI creator! πŸŽ‰

8

Module Seven

Module 7 Β· Racket AI Specialist – Machine Learning

πŸ€– Module Seven Β· Machine Learning – Teaching Computers to Learn

Certified Racket AI Specialist Β· The Heart of AI

πŸ“– Module Introduction

Hello, young teacher! πŸ‘‹ So far, we've been telling the computer exactly what to do. We gave it rules, and it followed them. But what if we could teach the computer to figure out the rules by itself?

Think about how you learn to ride a bicycle. Nobody gives you a manual with all the rules. You try, you fall, you try again, and slowly you get better. That's how Machine Learning works β€” the computer learns from examples and improves over time.

In this module, we will build our own simple machine learning system. We'll teach a computer to recognise patterns and make predictions. You'll see how AI really learns!

🧠 Fun fact: Machine Learning is how Netflix recommends movies, how self-driving cars see the road, and how your phone recognises your face!

🎯 Learning Objectives

After this module, you will be able to:

  • βœ”οΈ Understand what Machine Learning is and how it works.
  • βœ”οΈ Understand the difference between training and testing.
  • βœ”οΈ Build a simple classifier that learns from examples.
  • βœ”οΈ Use features to describe data.
  • βœ”οΈ Understand accuracy β€” how well a model performs.
  • βœ”οΈ Build a nearest neighbour classifier.
  • βœ”οΈ Train a model to make predictions on new data.

πŸ“š Warm-up Story Β· The Fruit Sorter

Imagine you work at a fruit market. Your job is to sort apples and oranges. You don't have a rule book. Instead, a farmer shows you examples: "This is an apple. It's red and round. This is an orange. It's orange and round."

After seeing many examples, you learn the pattern. When you see a new fruit, you can guess if it's an apple or orange. That's exactly how Machine Learning works β€” you show the computer lots of examples, and it learns the pattern.

Today, we'll build a fruit sorter in Racket β€” a machine learning system that learns to recognise fruits!

   Training phase:
   [Apple, red, round] β†’ apple
   [Orange, orange, round] β†’ orange
   [Apple, red, round] β†’ apple

   Testing phase:
   [New fruit, red, round] β†’ guess: apple!
  

🧩 Main Lessons

Lesson 1 Β· What is Machine Learning?

Definition: Machine Learning is a way for computers to learn from examples without being explicitly programmed with rules.

Why important: This is how AI becomes smart β€” by learning from data instead of following fixed rules.

Simple explanation: It's like teaching a dog new tricks. You don't give it a book; you show it what to do and reward it when it gets it right.

Real-life: Spam filters learn which emails are spam by looking at examples.

School: You learn math by doing many practice problems.

Home: You learn to cook by trying recipes and learning from mistakes.

Nigerian: Learning to speak your mother tongue by listening to your family.

Illustration:

   +-------------------+      +-------------------+
   |   Examples (data) | ---> |  Machine Learning | --->  Rules (model)
   +-------------------+      +-------------------+
         apples, oranges         can classify new fruits
  
πŸ“Œ Mini summary: Machine Learning is learning from examples instead of following fixed rules.

Lesson 2 Β· Training vs Testing

Definition: Training is when we show the computer examples to learn from. Testing is when we check how well it learned.

Why important: We need to know if our model works on new data, not just the examples it already saw.

Simple explanation: It's like studying for a test (training) and then taking the test (testing).

Real-life: A student practices math problems (training) and then takes an exam (testing).

School: Doing homework is training; the final exam is testing.

Home: Practicing a dance routine (training) and performing it (testing).

Nigerian: Learning to cook from your mother (training) and cooking for guests (testing).

Illustration:

   +------------+     +--------------+     +------------+
   |   Data     | --> |  Split data  | --> |  Training  | -->  Model
   +------------+     +--------------+     +------------+
                           |                       |
                           V                       V
                     +------------+        +------------+
                     |  Testing   |        |  Evaluate  |
                     +------------+        +------------+
  
πŸ“Œ Mini summary: Training is learning; testing is checking how well we learned.

Lesson 3 Β· Features – What Describes Our Data

Definition: Features are the characteristics of the data we use for learning. For a fruit, features could be colour, shape, and size.

Why important: The right features help the computer learn better.

Simple explanation: If you describe a person, you might use features like height, hair colour, and eye colour.

Real-life: To sort fruits, features are colour, shape, and size.

School: To describe a student, features are age, grade, and favourite subject.

Home: To describe a pet, features are size, colour, and breed.

Nigerian: To describe a car, features are brand, model, and colour.

Illustration:

   Fruit   β†’  [colour, shape, size]
   Apple   β†’  [red, round, medium]
   Orange  β†’  [orange, round, medium]
   Banana  β†’  [yellow, long, small]
  
πŸ“Œ Mini summary: Features are the characteristics we use to describe our data.

Lesson 4 Β· Labels – What We Want to Predict

Definition: The label is the answer we want the computer to predict. For a fruit, the label is the type of fruit (apple, orange, etc.).

Why important: The computer learns to map features to labels.

Simple explanation: It's like the answer key for a test.

Real-life: In a photo of a cat, the label is "cat".

School: In a test, the label is the correct answer.

Home: When sorting laundry, the label is "dark" or "light".

Nigerian: In a market, the label is the price.

Illustration:

   Training example: [red, round, medium]  β†’  apple (label)
   Training example: [orange, round, medium] β†’  orange (label)
  
πŸ“Œ Mini summary: Labels are the answers we want the computer to predict.

Lesson 5 Β· Representing Data in Racket

We can use lists to represent examples. Each example is a list of features, and we can store the label separately.

   (define apple-example '(red round medium))
   (define orange-example '(orange round medium))
   (define training-data
     '((red round medium apple)
       (orange round medium orange)
       (red round medium apple)
       (yellow long small banana)))
  

Or we can use structures for cleaner code.

πŸ“Œ Mini summary: We can represent training data as lists of features plus a label.

Lesson 6 Β· The Nearest Neighbour Algorithm

Definition: Nearest Neighbour is a simple machine learning algorithm that classifies a new example by finding the most similar example in the training data.

Why important: It's simple, powerful, and easy to understand.

Simple explanation: If you want to know what a new fruit is, find the fruit that looks most like it and call it that.

Real-life: If you see a new bird, compare it to birds you know.

School: If you have a new word, find the one that looks most like it.

Home: If you find a toy you don't recognise, compare it to toys you know.

Nigerian: If you see a new type of cloth, compare it to known fabrics.

Illustration:

   New fruit: [red, round, medium]
   Compare to training:
   [red, round, medium] β†’ apple (distance 0)
   [orange, round, medium] β†’ orange (distance 1)
   [yellow, long, small] β†’ banana (distance 3)
   Nearest is apple β†’ predict apple!
  
πŸ“Œ Mini summary: Nearest Neighbour finds the most similar example and copies its label.

Lesson 7 Β· Measuring Similarity – Distance

We need a way to measure how similar two examples are. A simple way is to count how many features are different.

   (define (distance a b)
     (length (filter (lambda (x) (not (equal? x (car b))))
                     (map list a b))))
   ; Or simpler: count differences
   (define (diff-count a b)
     (if (null? a)
         0
         (if (equal? (car a) (car b))
             (diff-count (cdr a) (cdr b))
             (+ 1 (diff-count (cdr a) (cdr b))))))
  
πŸ“Œ Mini summary: Distance measures how different two examples are.

Lesson 8 Β· Implementing Nearest Neighbour

Now we can write the full classifier.

   (define (classify data features)
     (define (distance-to-example ex)
       (diff-count features (drop-right ex 1)))
     (define sorted-data
       (sort data (lambda (a b) (< (distance-to-example a) (distance-to-example b)))))
     (last (car sorted-data)))  ; the label is the last element
  
πŸ“Œ Mini summary: We sort training examples by similarity and pick the closest one's label.

Lesson 9 Β· Training and Testing Our Classifier

Let's train our model and test it.

   (define training-data
     '((red round medium apple)
       (orange round medium orange)
       (red round medium apple)
       (yellow long small banana)
       (green round small grape)
       (purple round medium grape)))
   (classify training-data '(red round medium)) β†’ apple
   (classify training-data '(orange round medium)) β†’ orange
   (classify training-data '(yellow long small)) β†’ banana
  
πŸ“Œ Mini summary: Our classifier works on training data. Now we test it on new data.

Lesson 10 Β· Accuracy – How Good Is Our Model?

Definition: Accuracy is the percentage of correct predictions our model makes on test data.

Why important: It tells us how well our model will work in the real world.

Simple explanation: If you get 8 out of 10 questions right on a test, your accuracy is 80%.

Real-life: A doctor's diagnostic accuracy is how often they are correct.

School: Your score on a test is your accuracy.

Home: How often you correctly guess the weather is your accuracy.

Nigerian: How often you correctly predict the price of goods is your accuracy.

Illustration:

   Test examples: 10
   Correct predictions: 8
   Accuracy = 8/10 = 80%
  
πŸ“Œ Mini summary: Accuracy measures how often our model is correct.

Lesson 11 Β· Improving Our Classifier – K-Nearest Neighbours

Instead of just looking at the nearest neighbour, we can look at the K nearest neighbours and take a vote. This is called K-Nearest Neighbours (KNN).

Why important: It makes our model more robust to noisy data.

Simple explanation: Instead of asking one friend for advice, ask five friends and go with the majority opinion.

   (define (k-classify data features k)
     (define (label-counts lst)
       ; count how many of each label in the list
       (define (count-label label lst)
         (length (filter (lambda (x) (equal? (last x) label)) lst)))
       ; ... implement majority vote
       )
  
πŸ“Œ Mini summary: K-Nearest Neighbours uses multiple neighbours and takes a vote.

Lesson 12 Β· Building a Real-World Classifier – Animal Recognizer

Let's build a classifier that recognises animals based on features: size, habitat, and diet.

   (define animal-data
     '((large land herbivore elephant)
       (small land herbivore rabbit)
       (large water carnivore shark)
       (medium land carnivore lion)
       (small air herbivore bird)
       (medium land omnivore bear)))
   (classify animal-data '(medium land carnivore)) β†’ lion
  
πŸ“Œ Mini summary: We can use our classifier for any problem with features and labels.

Lesson 13 Β· Putting It All Together – A Complete ML System

Let's build a complete system that: 1) Loads data, 2) Splits it into training and testing, 3) Trains a model, 4) Tests it, 5) Reports accuracy.

   (define (ml-system data test-data)
     (define correct
       (length (filter (lambda (test)
                         (equal? (classify data (drop-right test 1))
                                 (last test)))
                       test-data)))
     (/ correct (length test-data)))
  

You built a complete machine learning system!

πŸ“Œ Mini summary: We combined everything into a complete machine learning pipeline.

πŸ“– Key Vocabulary

  • Machine Learning: Learning from examples.
  • Training: Learning phase.
  • Testing: Evaluation phase.
  • Features: Characteristics of data.
  • Label: What we want to predict.
  • Nearest Neighbour: Classifies by closest example.
  • Accuracy: Percentage of correct predictions.
  • K-Nearest Neighbours (KNN): Uses K nearest neighbours and votes.

🧠 Important Concepts

  • Data is key: Better data = better learning.
  • Features matter: Choose features that help distinguish.
  • Overfitting: When a model is too specific to training data.
  • Generalisaton: Model works well on new data.

πŸ“˜ Step-by-Step Explanations

How to build a machine learning system:

  1. Collect data (examples with features and labels).
  2. Split into training and testing sets.
  3. Choose an algorithm (like Nearest Neighbour).
  4. Train the model on the training data.
  5. Test the model on the testing data.
  6. Calculate accuracy.
  7. Use the model to make predictions on new data.

🌍 Real-life Examples

  • Spam detection: features = words in email, label = spam/not.
  • Face recognition: features = face measurements, label = person.
  • Medical diagnosis: features = symptoms, label = disease.

πŸ‡³πŸ‡¬ Nigerian Examples

  • Predicting yam prices: features = season, region, quality, label = price.
  • Traffic prediction: features = time, day, location, label = traffic level.
  • Language identification: features = words, label = language (Yoruba, Igbo, Hausa).

🎈 Fun Examples

  • Recognize PokΓ©mon: features = colour, size, type, label = PokΓ©mon name.
  • Predict movie ratings: features = genre, length, actors, label = rating.
  • Guess the animal: features = habitat, food, size, label = animal.

🏠 Everyday Examples

  • Sorting laundry: features = colour, fabric, label = light/dark/delicate.
  • Choosing a movie: features = genre, length, actors, label = watch/don't watch.
  • Deciding what to eat: features = taste, health, price, label = choose/not choose.

πŸ§‘β€πŸ« Teacher Notes

Use physical examples β€” show different fruits and ask students to identify them. Explain that the computer does this with numbers. Emphasize that data quality matters. Let students create their own small datasets and train classifiers.

πŸ‘ͺ Parent Tips

Ask your child to teach you how the classifier works. Create a simple dataset at home (e.g., toy names with features: colour, size, type). Let them show you how the computer learns.

🌟 Interesting Facts

  • The first machine learning program was written in 1951.
  • Machine learning is used to detect diseases from X-rays.
  • Self-driving cars use machine learning to understand the road.

πŸ€” Did You Know?

Machine learning models can learn to play games better than humans. The AlphaGo model beat the world champion at the game of Go!

🧾 Remember This

  • Machine Learning learns from examples.
  • Training is learning; testing is checking.
  • Features describe the data.
  • Labels are what we want to predict.
  • Nearest Neighbour is a simple learning algorithm.

⚠️ Common Mistakes

  • Testing on the same data used for training (cheating).
  • Using too few examples (not enough to learn).
  • Using irrelevant features (confuses the model).
  • Overcomplicating when simple works.

βœ… Best Practices

  • Always split data into training and testing.
  • Use enough examples (at least 10 per class).
  • Choose features that matter.
  • Start simple (Nearest Neighbour) before complex.

πŸ“Š ASCII Illustrations

   Machine Learning Flow:
   +------------------+
   |  Collect Data    |
   +--------+---------+
            |
            V
   +--------+---------+
   |  Split Data      |
   |  (Train/Test)    |
   +--------+---------+
            |
            V
   +--------+---------+
   |  Train Model     |
   +--------+---------+
            |
            V
   +--------+---------+
   |  Test Model      |
   +--------+---------+
            |
            V
   +--------+---------+
   |  Evaluate (Accuracy)|
   +--------+---------+
            |
            V
   +--------+---------+
   |  Predict New Data |
   +------------------+
  
   KNN Voting:
   New example β†’ find K nearest
       |
       V
   +-----+-----+-----+
   |     |     |     |
   Apple Orange Apple
   (2)    (1)
   Vote: Apple!
  

πŸ“‹ Comparison Table

AlgorithmHow it worksGood for
Nearest NeighbourFind closest exampleSmall datasets
K-Nearest NeighboursVote among K neighboursNoisy data

πŸ“Œ End-of-Module Summary

You've built your first machine learning system! You learned about training and testing, features and labels, and implemented the Nearest Neighbour algorithm. You even built a K-Nearest Neighbours classifier. These are the same ideas used in real AI systems β€” you're now a machine learning creator!

❓ Frequently Asked Questions (10)

  1. What is Machine Learning? β€” Learning from examples.
  2. What is training? β€” The learning phase.
  3. What is testing? β€” Checking how well we learned.
  4. What are features? β€” Characteristics of the data.
  5. What is a label? β€” The answer we want to predict.
  6. What is Nearest Neighbour? β€” Classifies by closest example.
  7. What is accuracy? β€” Percentage of correct predictions.
  8. What is KNN? β€” Uses K neighbours and votes.
  9. Why do we split data? β€” To test on unseen data.
  10. Can I use this for anything? β€” Yes, any problem with features and labels.

πŸ“ Review Questions (15)

  1. What is Machine Learning?
  2. What is the difference between training and testing?
  3. What are features?
  4. What is a label?
  5. How does Nearest Neighbour work?
  6. What is accuracy?
  7. What is K-Nearest Neighbours?
  8. Why do we split data into training and testing?
  9. Write a function to calculate distance between two examples.
  10. How do you classify a new example with Nearest Neighbour?
  11. What is a good accuracy score?
  12. Give an example of a machine learning problem.
  13. What is overfitting?
  14. How can you improve a classifier?
  15. What is the difference between rules-based AI and machine learning?

✏️ Fill-in-the-Blank

  1. ______ learning learns from examples.
  2. ______ is the learning phase.
  3. ______ is the evaluation phase.
  4. ______ describe the data.
  5. ______ is what we want to predict.

βœ… True or False

  1. Machine Learning doesn't need examples. (False)
  2. Training and testing should use the same data. (False)
  3. Features describe the data. (True)
  4. A label is what we predict. (True)
  5. Nearest Neighbour is a complex algorithm. (False)

πŸ”˜ Multiple Choice (15)

  1. What is Machine Learning? A) learning from examples B) following rules C) doing math D) storing data β†’ A
  2. What is training? A) learning phase B) evaluation phase C) storing data D) deleting data β†’ A
  3. What is testing? A) evaluation phase B) learning phase C) storing data D) deleting data β†’ A
  4. What are features? A) characteristics B) labels C) rules D) examples β†’ A
  5. What is a label? A) what we predict B) a characteristic C) a rule D) a feature β†’ A
  6. How does Nearest Neighbour work? A) finds closest example B) averages all examples C) picks random D) follows rules β†’ A
  7. What is accuracy? A) % correct predictions B) number of examples C) time taken D) memory used β†’ A
  8. What is KNN? A) K nearest neighbours B) K features C) K labels D) K rules β†’ A
  9. Why split data? A) to test on unseen data B) to make it slower C) to delete data D) to add features β†’ A
  10. What is a good use of ML? A) spam detection B) adding numbers C) sorting lists D) printing text β†’ A
  11. What is overfitting? A) too specific to training B) too general C) too fast D) too slow β†’ A
  12. Which is simpler? A) Nearest Neighbour B) Deep Learning C) KNN D) Random Forest β†’ A
  13. What does distance measure? A) similarity B) size C) time D) speed β†’ A
  14. What is a feature for a fruit? A) colour B) price C) name D) taste β†’ A
  15. What is a label for a fruit? A) type (apple) B) colour C) size D) shape β†’ A

πŸ”— Matching

TermMatch
1. FeaturesA. what we predict
2. LabelB. characteristics
3. TrainingC. learning phase

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

πŸ“ Short Answer

  1. Explain the difference between training and testing.
  2. What is the role of features in machine learning?
  3. Write a function that calculates the accuracy of a classifier.

πŸ“– Scenario-based Exercises

Scenario: You are building a system to predict if it will rain tomorrow. Features: temperature, humidity, wind speed. Label: rain/no rain. How would you set up the machine learning system?

Answer: Collect historical data with these features and the label, split into training/testing, use Nearest Neighbour or KNN, evaluate accuracy.

πŸ‘₯ Group Activity

Each group creates a dataset of 20 examples for a classification problem (e.g., animal recognition, food classification). Implement a Nearest Neighbour classifier and test it. Present results.

πŸ§‘β€πŸ’» Individual Activity

Build a classifier that predicts whether a student will pass an exam based on study hours and attendance. Create your own data and test it.

πŸ’¬ Classroom Discussion Questions

  • What makes a good feature for a classifier?
  • What happens if you have too few examples?
  • How is machine learning different from traditional programming?

πŸ› οΈ Mini Project

Build a "PokΓ©mon type classifier" that predicts the type of a PokΓ©mon (fire, water, grass) based on features like colour, height, and weight.

πŸ“‹ Practical Assignment

Implement a K-Nearest Neighbours classifier with K=3. Test it on a dataset of your choice and report the accuracy.

πŸ† Challenge Exercise

Implement a weighted KNN where closer neighbours have more influence on the vote.

πŸ”‘ Quiz Answers

Multiple choice answers: 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

  • Machine Learning learns from examples.
  • Training = learning, Testing = evaluation.
  • Features describe data; labels are predictions.
  • Nearest Neighbour is a simple, powerful algorithm.
  • Accuracy measures model performance.

πŸš€ Preparation for the Next Module

In Module Eight, we'll explore AI in the Real World β€” how AI is used in robotics, healthcare, games, and more. We'll also talk about the ethics of AI and how to build responsible systems. Get ready to see your AI skills in action!


πŸŽ‰ You've completed Module Seven Β· You are now a Machine Learning creator! πŸŽ‰

πŸ† Get Certified

πŸ”’

Earn this certificate

Every lesson is already free to read. Sign up, pass the exam, and unlock Practice Tools plus a verified certificate with your name on it β€” ₦4,000/month.

πŸŽ“ Sign Up & Unlock for ₦4,000/month
πŸ› οΈ Practice Tools
Hands-on simulators & labs - subscription required.
β†’
🎯 Internship Tasks
Real-world tasks to build your portfolio - try them free for 7 days, no card required.
β†’