CS 1102: Summary of New Racket Operators

During the slideshow exercise, we've seen several new Racket constructs. Here's a brief recap of those constructs. More details appear in the DrRacket helpdesk.


begin takes any number of expressions as arguments. It evaluates each one in turn and returns the result of the last one. Note that the results of all the expressions except the last get thrown away, so begin is only useful if the non-last expressions perform side-effects such as set! and printf operations.


set! is the assignment operator in Racket. It takes two arguments: a variable name and an expression. set! changes the value of the given variable to the result of the expression. Here's an example:

    (define count 0)
    (set! count (+ 1 count))

We expect you to use set! sparingly in your code. In particular, you should only use set! on a variable when you have one function that changes the value of the variable and another that uses the value of the variable (unless you are implementing something like a counter). In particular, you should NOT use set! to write C++ style programs in Racket. While you can write code that works that way, they defeat the point of programming functionally. We will deduct point for gratuitous uses of set!.


for-each is like map, expect it throws away the answers to running the function on each element of the list rather than gathering the answers into a list. Use for-each when you want to run a side-effecting function on each element of a list. For example, to print out the elements of a list to the screen, you can write:

    (for-each printf (list "hi" "mom"))


printf is the basic string output routine in Racket. It takes a variable number of arguments. You can give it a single string as output, or you can give it a string with placeholders and enough other arguments to fill the placeholders. Denote a placeholder with ~a. Insert a newline with ~n. For example

     (printf "Here's placeholder one ~a and placeholder two ~a~n"
             'value1 'value2)

where value1 and value2 could be any scheme data (numbers, lists, structs, etc).


format lets you create strings in similar style to printf, but format returns the string instead of printing it out. For example:

    (format "My ~a is ~a" 'name 'Kathi)
  = "My name is Kathi"

Format comes in handy when you want to combine several data items into a single string.


Read is the standard input function. Read will take characters from the prompt until you enter whitespace and return that sequence of characters as a symbol.

Here's an example combining read and printf -- type it in and try it.

   (define (age-to-year)
       (printf "Enter your age: ")
       (let ([age (read)])
         (printf "You were born in ~a or ~a~n"
                 (- 2003 (+ 1 age)) (- 2003 age)))))