On this page:
1 Mutually recursive data
2 Mutual recursion with lists
3 Mutual-recursion check
8.12

Lecture 20: Mutual recursion🔗

You don’t need to submit anything for this lecture. But we strongly encourage you to submit it as soon as possible using Handin as assignment lecture20, to practice and get automatic feedback.

1 Mutually recursive data🔗

; A TwoTree is one of:
; - Number
; - (make-two ThreeTree ThreeTree)
(define-struct two [first second])
 
; A ThreeTree is one of:
; - Number
; - (make-three TwoTree TwoTree TwoTree)
(define-struct three [first second third])

Exercise 1. Write 3 more examples of TwoTrees and ThreeTrees. Call the TwoTrees two1 two2 two3. Call the ThreeTrees three1 three2 three3.

Exercise 2. Design two functions: one called sum-twotree that sums all the numbers in a TwoTree, and one called sum-threetree that sums all the numbers in a ThreeTree.

Exercise 3. Design a function add-to-twotree that adds a given number to all the numbers in a given TwoTree and a function add-to-threetree that adds a given number to all the numbers in a given ThreeTree.

2 Mutual recursion with lists🔗

; A FamilyTree is (make-ft String
;                          Number
;                          [ListOf FamilyTree])
(define-struct ft [name age children])
 
; A [ListOf FamilyTree] is one of:
; - empty
; - (cons FamilyTree [ListOf FamilyTree])

Exercise 4. Design a function count-ft that counts all the people in a given FamilyTree and a function count-loft that counts all the people in a given [ListOf FamilyTree]. Can you do it using foldr?

Exercise 5. Design a function growup-ft that adds 1 to the ages of all the people in a given FamilyTree and a function growup-loft that adds 1 to the ages of all the people in a given [ListOf FamilyTree]. Can you do it using map?

The code written in the videos above is available for your reference. To download it, don’t use “Save Page As” or “Save As”; use “Save Link As” or “Download Linked File” in your Web browser. If you can’t find the command, try right-clicking or two-finger-tapping or long-pressing.

3 Mutual-recursion check🔗

Did you get it? Click the button

Check your answer using “Show answer” above. Did you get it right? If not, click the button again to get another set, and keeping doing it until you get it right without peeking at the answer.

You don’t need to submit anything for this check.

Optional: Read Chapters 19–22 of the textbook.