Page 2: Writing Recursive Reporters

Unit 8, Lab 1, Page 2

On this page, you’ll build a recursive factorial block and several recursive blocks that handle strings.

Say 9! as “nine factorial”, not NINE!

The factorial function, n!, is defined to be the product of the integers from 1 to n.

  1. The value of 9! is 362,880. Find the value of 10!.

    Don’t forget Betsy’s advice: base cases are important!

  1. Describe the relationship between 37! and 36!.

  1. Use these ideas to build a factorial block using a recursive reporter.

Recursive commands often have structure like this, with multiple commands in the recursive case:

Recursive procedures can even have multiple recursive calls (tree is a good example; we called tree twice from within a single call to tree).

recursion(input){if(base case?(input){do something simple} else{do stuff; recursion(smaller input); do stuff}}

Recursive reporters have a different structure because they can report only one value. Since the report block reports an answer, you’ll need to build the answer before or inside the report block call. So, this isn’t possible:

You can’t even build this script because you won’t be allowed to connect any block below a report block.

Cannot do this: recursive reporter(input){if(base case?(input){report (something simple)} else{report something; report(recursive reporter(smaller input)); report something}}

Word processing programs count the number of words and letters in documents. One way to count the number of letters in a phrase is to use a recursive reporter.

  1. The phrase “in the course of human events” has 24 letters. How many letters are there in the phrase “When in the course of human events”?

  1. Recursion always needs a base case to stop the script from calling itself forever. What sort of base case might we use for this situation?

  1. Create a letter count block that takes a list of words as input and reports the total number of letters in all the words. The all but first of block may be useful, but there is more than one way to do this.
    letter count(list{We, the. People, of, the, United, States}) reporting 28

  1. Create your own version of the join words block. This block inputs a list and outputs a string sentence, with spaces:
    my join words(list{We, the. People, of, the, United, States}) reporting -We the People of the United States

The list operations all but first of and in front of are frequently used in recursive reporters.

  1. Build this plurals block, then describe how it works.
    plurals(words){if(empty?(words)){report(empty list)} else{report((join (item 1 of words)(s) in front of (plurals(all but first of (words)))}}