Homework 3

Please read chapter 6: Itemizations and Structures and chapter 7: Summary in the textbook.

Be sure to include type, purpose, definition and tests for all functions.

Include the following at the top of your homework:

#lang typed/racket

(require typed/test-engine/racket-tests)
And include (test) at the bottom of your homework.

Problem 1

Add the following to your definitions window:

(define-struct Cylinder
  ([r : Real]
   [h : Real]))

(define-struct Sphere
  ([r : Real]))

(define-struct Cube
  ([s : Real]))

(define-struct Cone
  ([r : Real]
   [h : Real]))

(define-type Shape (U Sphere Cylinder Cube Cone))

You may recall that the U allows us to form a union type. The above creates 5 new types: 4 structures and one union type. The type Shape can be any of the 4 structures. We call Sphere a subtype of Shape, and a Sphere is a valid input to any function that expects a Shape as input.

Write a function volume that takes a Shape as input and produces a Real as output. It should compute the volume of any shape.

It may be quite helpful to first write a volume function for each shape (Cylinder-volume, Sphere-volume, etc.). You can use these functions to make the shape volume function much simpler.

We talked very briefly about selectors in lecture, and you will need them for this problem. Selectors are created every time you define a new structure. The name of the selector is the name of the struct followed by a question mark (e.g. Cylinder?, Sphere?, etc.). They will take any input and produce as output a Boolean indicating wether or not the input matched the type in question. For example, (Cylinder? (make-Cylinder 1 .5)) is true while (Cylinder? (make-Cube 3)) is false.

Problem 2

The Fibonacci sequence is defined as follows:

F(1) = 1
F(2) = 1
F(n) = F(n-1) + F(n-2)

Define a function fib that takes a number n as input and computes the nth number in the Fibonacci sequence.

Submit your work in your repository in hw4/hw4.rkt by noon Wednesday, June 28.