January 4, 1995
Due in quiz sections January 12, 1995
+,
first, rest, cons,
length, equal, and not. You don't
have to hand in anything for this question.
(cons 1 (cons 2 nil))
______ -------
| | | | | /|
| o | -|----->| o | / |
|_|_|__| |_|_|/__|
| |
| |
v v
1 2
(list 1 2)
______ -------
| | | | | /|
| o | -|----->| o | / |
|_|_|__| |_|_|/__|
| |
| |
v v
1 2
(cons (cons 'x nil) (cons 'x nil))
______ -------
| | | | | /|
| o | -|----->| o | / |
|_|_|__| |_|_|/__|
| |
| |
v v
------- X
| | /|
| o | / |
|_|_|/__|
|
|
v
X
One answer could be: A type safe language does not allow you to use types incorrectly, i.e. in a way which could cause an incorrect result to be produced. If mixing of types is allowed, the language makes sure that the correct operation with the correct types is invoked. LISP for instance allows (+ 3 3.0). It will convert the integer 3 to the float 3.0 and add it to the float 6.0 producing the correct result. In a type unsafe language on the other hand, it is not guaranteed that in all cases types are used correctly. A LISP example:
(defun bad (x)
(+ x ""))
(bad 3) will produce a type error at run time when (+ 3 nil) is executed the
system detects that the arguments to "+" are incorrect, as it expects numbers
and one argument is the empty string:
Error: "" is an illegal argument to +
[condition type: TYPE-ERROR]
You can define it in C as follows:
int bad (int x)
{
return (x + "");
}
It compiles fine. Running it calling foo(3) produces
(using gcc on a decstation)
268439875
Definitely not what you wanted! This example also shows that C is unsafe.
Statically typed languages do type checking at compile time, dynamically typed
languages at run time.
number-stuff that takes a
single floating-point argument n and returns a list consisting of n, n
squared, n cubed, and the square root of n. Example:
(number-stuff 3.0) evaluates to
(3.0 9.0 27.0 1.7320508)
You don't need to worry about checking for non-numeric or negative arguments.
(defun number-stuff (n) (list n (* n n) (* n n n) (sqrt n)))
next-color
that takes a symbol (one of green, yellow, or red) representing a stoplight
color, and returns the next color in the light's sequence. If the argument
isn't one of these symbols return the atom huh.
Examples:
(next-color 'green) evaluates to yellow
(next-color 'yellow) evaluates to red
(next-color 'red) evaluates to green
(next-color (next-color 'green)) evaluates to red
(next-color 'purple) evaluates to huh
(defun next-color (color)
(cond ((equal color 'green) 'yellow)
((equal color 'yellow) 'red)
((equal coler 'red) 'green)
(t 'huh)))