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.
Capstone project: build an end-to-end AI system in Racket β from data ingestion to inference β with full documentation & performance evaluation.
Certified Racket AI Specialist Β· Foundation
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!).
By the end of this module, you will be able to:
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 |
+-----------------+
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
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 | +-------------+ +----------------+ +-----------+
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
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
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)
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")
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"
define to create them.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"
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
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)
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!
How to write your first Racket program:
(+ 5 6) in the interactions window.(define age 12).age β Racket shows 12.(define (double x) (* x 2)).(double 5) β you get 10!(- 10 3)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.
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!
Racket was originally made for teaching, so it's perfect for beginners like you. And many AI researchers use it to test new ideas!
"hello" not hello.= instead of equal? for comparing.(+ 2 3) is correct, (2 + 3) is not.(+ 2 3 is missing a ).age not x.
+--------+ +--------+ +--------+
| Input | ---> | Racket | ---> | Output |
+--------+ +--------+ +--------+
( + 5 3 ) computes 8
Flow of a program: Start β Get Input β Process β Show Result β End
| Concept | English analogy | Racket example |
|---|---|---|
| Variable | Box with label | (define age 12) |
| Function | Recipe | (define (square x) (* x x)) |
| List | Shopping list | '(1 2 3) |
| If | Decision | (if (> age 8) "big" "small") |
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!
| Term | Match |
|---|---|
| 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
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))
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.
Write a Racket expression that adds 10 and 20, multiplies the result by 2, and stores it in a variable called "result".
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.)
Write a Racket program that takes your age and tells you if you are old enough to ride a rollercoaster (age > 12).
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).)
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.
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! π
Certified Racket AI Specialist Β· Building Intelligence
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!
After this module, you will be able to:
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
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
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)
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
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"
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"
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
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
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"
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")
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"
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
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!
How to write a decision program:
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.
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!
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!
= to compare strings β use equal?.and and or are operators, not keywords.else in cond β your program might return nothing.cond for more than 3 options.
Decision Flow:
+---------+ +--------+ +--------+
| Condition | --> | #t? | --> | Action1 |
+---------+ +--------+ +--------+
|
V
+--------+ +--------+
| #f? | --> | Action2 |
+--------+ +--------+
AND logic:
Input1 ---+
AND ---> Output
Input2 ---+
| Operator | Meaning | Example | Result |
|---|---|---|---|
| > | greater than | (> 10 5) | #t |
| < | less than | (< 2 5) | #t |
| = | equal (numbers) | (= 3 3) | #t |
| equal? | equal (any type) | (equal? "hi" "hi") | #t |
| and | both true | (and #t #t) | #t |
| or | at least one true | (or #f #t) | #t |
| not | flips | (not #t) | #f |
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.
| Term | Match |
|---|---|
| 1. #t | A. false |
| 2. #f | B. true |
| 3. cond | C. many choices |
| 4. if | D. two choices |
Answers: 1-B, 2-A, 3-C, 4-D
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")
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.
Write a function called can-vote? that takes age and returns #t if age β₯ 18, else #f.
Create a "traffic light" program. Use cond with a color input: "red" β stop, "yellow" β wait, "green" β go, else β "invalid".
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.
Write a function that takes three numbers and returns the largest. Use cond and comparisons.
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.
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! π
Certified Racket AI Specialist Β· Power of Doing Things Again and Again
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!
After this module, you will be able to:
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
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
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!
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)
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
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)
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)
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
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.
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.
In Racket, we use recursion instead of traditional loops (like 'for' or 'while' in other languages). Recursion is more functional and elegant.
| Language | Loop style |
|---|---|
| Python | for i in range(5): print(i) |
| Racket | (define (loop n) (if (> n 0) (begin (display n) (loop (- n 1))) 'done)) |
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.
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!
How to write a recursive function:
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.
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.
Racket's map can work with multiple lists at the same time! For example: (map + '(1 2) '(3 4)) β '(4 6).
rest to shrink the list.map and filter β map returns same length, filter returns shorter.foldl with wrong initial value.
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]
| Function | What it does | Returns |
|---|---|---|
| map | transforms each item | list of same length |
| filter | keeps items that pass test | shorter list |
| foldl | combines all items | single value |
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.
| Term | Match |
|---|---|
| 1. map | A. combines items |
| 2. filter | B. transforms each |
| 3. fold | C. keeps some |
| 4. recursion | D. calls itself |
Answers: 1-B, 2-C, 3-A, 4-D
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))
Each group writes a function that takes a list of words and returns a list of their lengths. Use map.
Write a recursive function that returns the last element of a list.
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.
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.
Write a recursive function that reverses a list. (Hint: append the first item to the reverse of the rest.)
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.
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! π
Certified Racket AI Specialist Β· Building Smart Containers
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.
After this module, you will be able to:
struct.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)
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)
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
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.
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
We can add, find, and update values in alists. Racket provides functions like assoc and alist-update.
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
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.
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.
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)))))
| Structure | Use when | Example |
|---|---|---|
| List | Simple ordered data | scores of a game |
| Struct | Related fields | student record |
| Association list | Lookup by key | dictionary |
| Tree | Hierarchical data | family tree |
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!
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.
How to create a structure and use it:
(struct person (name age))(define p (person "Ada" 12))(person-name p) β "Ada"(list (person "Bob" 10) (person "Eve" 11))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.
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.
Racket's struct can automatically generate functions for you: a constructor, field accessors, and even a predicate (like student?).
struct before creating an instance.assoc on an alist with improper formatting.student, book, etc.empty? to check for empty lists and trees.Structure example: +------------------------+ | Student | +------------------------+ | name: "Ade" | | age: 12 | | class: "JSS2" | +------------------------+
Tree example:
+-----+
| 10 | (root)
+-----+
/ \
+---+ +---+
| 5 | | 15 |
+---+ +---+
/ \ \
+---+ +---+ +---+
| 2 | | 7 | | 20 |
+---+ +---+ +---+
| Structure | Use | Access |
|---|---|---|
| List | ordered items | first, rest |
| Struct | named fields | field functions |
| Alist | lookup | assoc |
| Tree | hierarchy | recursive traversal |
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.
| Term | Match |
|---|---|
| 1. struct | A. key-value pairs |
| 2. alist | B. hierarchical data |
| 3. tree | C. custom fields |
Answers: 1-C, 2-A, 3-B
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.
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.
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.
Build a "library manager" that stores books (title, author, year) and allows you to add, list, and find books by author.
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.
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.)
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.
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! π
Certified Racket AI Specialist Β· Mastering Hierarchies
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!
After this module, you will be able to:
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
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
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.
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))))))
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)))))
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
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))]))
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))))))
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))))))
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.
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.
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!
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!
How to traverse a tree:
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.
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.
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!
empty? to check for no children.map and fold for child processing.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
| Traversal | Order | Use |
|---|---|---|
| Pre-order | Node, children | Copying trees |
| Post-order | Children, node | Calculating totals |
| In-order | Left, node, right | Sorted output |
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!
| Term | Match |
|---|---|
| 1. Pre-order | A. children first |
| 2. Post-order | B. node first |
| 3. Leaf | C. no children |
Answers: 1-B, 2-A, 3-C
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.
Each group designs a decision tree for choosing a vacation destination. Questions: budget, beach or mountains, etc.
Write a function that counts the number of leaves in a tree.
Build a decision tree that helps choose a pet. Questions: Do you have a yard? Do you like walking? etc.
Implement a decision tree for a restaurant recommendation based on cuisine preference and budget.
Write a function that flattens a tree into a list using pre-order traversal.
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.
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! π
Certified Racket AI Specialist Β· The Creative Side of AI
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!
After this module, you will be able to:
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!)
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
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
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!
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!
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"
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)))
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)
β *
***
*****
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)
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)
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"
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)))
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!
How to build a generator:
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.
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!
The first generative AI programs in the 1960s could generate simple poetry. Today, they can write entire novels!
random for variety.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!
| Technique | How it works | Example |
|---|---|---|
| Random pick | Pick random item | (pick-random names) |
| Combination | Mix multiple picks | (string-append name action place) |
| Template | Fill in blanks | "The ~a ~a in the ~a" |
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!
| Term | Match |
|---|---|
| 1. Generative | A. creates new things |
| 2. Random | B. by chance |
| 3. Template | C. pattern with blanks |
Answers: 1-A, 2-B, 3-C
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.
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.
Build a generator that creates new pet names by combining syllables.
Build a "magic spell" generator. Create lists of words that sound magical and combine them to create new spells with "powers".
Build a generator that creates new Nigerian dish descriptions. Use ingredients, cooking methods, and tasty words.
Build a generator that creates simple poems. Use rhyme patterns and random word selection.
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.
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! π
Certified Racket AI Specialist Β· The Heart of AI
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!
After this module, you will be able to:
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!
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
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 |
+------------+ +------------+
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]
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)
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.
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!
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))))))
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
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
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%
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
)
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
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!
How to build a machine learning system:
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.
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.
Machine learning models can learn to play games better than humans. The AlphaGo model beat the world champion at the game of Go!
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!
| Algorithm | How it works | Good for |
|---|---|---|
| Nearest Neighbour | Find closest example | Small datasets |
| K-Nearest Neighbours | Vote among K neighbours | Noisy data |
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!
| Term | Match |
|---|---|
| 1. Features | A. what we predict |
| 2. Label | B. characteristics |
| 3. Training | C. learning phase |
Answers: 1-B, 2-A, 3-C
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.
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.
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.
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.
Implement a K-Nearest Neighbours classifier with K=3. Test it on a dataset of your choice and report the accuracy.
Implement a weighted KNN where closer neighbours have more influence on the vote.
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.
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! π