Friday, March 2, 2007

How to Design Programs - 2.4 Errors

Here are the exercises and my solotions of Section 2.4, called "Errors", in How to Design Programs.

Exercise 2.4.1.

Evaluate the following sentences in DrScheme, one at a time:

(+ (10) 20)
(10 + 20)
(+ +)

Read and understand the error messages.

Solution

> (+ (10) 20)
function call: expected a defined name or a primitive operation name after an open parenthesis, but found a number

The number 10 shouldn't be between parentheses here.

> (10 + 20)
function call: expected a defined name or a primitive operation name after an open parenthesis, but found a number

The number 10 is at the wrong position, it should read (+ 10 20)

> (+ +)
+: this primitive operator must be applied to arguments; expected an open parenthesis before the primitive operator name

There should be a value or expression at that position (followed by a second value or expression).

Exercise 2.4.2.

Enter the following sentences, one by one, into DrScheme's Definitions window and click Execute:

(define (f 1)
  (+ x 10))

(define (g x)
  + x 10)

(define h(x)
  (+ x 10))

Read the error messages, fix the offending definition in an appropriate manner, and repeat until all definitions are legal.

Solution

(define (f 1)
  (+ x 10))
__________

define: expected a name for the function's 1st argument, but found a number

The faulty 1 should be replaced by a x:

(define (f x)
  (+ x 10))

(define (g x)
  + x 10)
__________

define: expected only one expression for the function body, but found at least one extra part

There is a open parenthesis missing, and a close parenthesis should be added to the end:

(define (g x)
  (+ x 10))

Exercise 2.4.3.

Evaluate the following grammatically legal Scheme expressions in DrScheme's Interactions window:

(+ 5 (/ 1 0))

(sin 10 20)

(somef 10)

Read the error messages.

Solution

> (+ 5 (/ 1 0))
/: division by zero
> (sin 10 20)
sin: expects 1 argument, given 2: 10 20
> (somef 10)
reference to an identifier before its definition: somef

Exercise 2.4.4.

Enter the following grammatically legal Scheme program into the Definitions window and click the Execute button:

(define (somef x)
  (sin x x))

Then, in the Interactions window, evaluate the expressions:

(somef 10 20)

(somef 10)

and read the error messages. Also observe what DrScheme highlights.

Solution

> (somef 10 20)
somef: this procedure expects 1 argument, here it is provided 2 arguments

There should only be one argument, e.g. (somef 10)

(define (somef x)
  (sin x x))

__________

> (somef 10)
sin: expects 1 argument, given 2: 10 10

The sin primitive accepts only one argument, it should read (sin x) in the definition.

No comments: