The Grinnell Scheme Web: Type
predicates

If any variable can have a value of any type, how can you avoid giving operands of one type to procedures that expect and accept only values of some other type? What will happen if, say, you try to add two Boolean values?

Well, to take the last question first, the program will crash if you give a procedure operands of some unexpected type:

> (+ #f #t)

ERROR: +: Wrong type in arg1 #f
It's the programmer's responsibility to prevent such disasters by keeping track of what kind of value is being stored in each variable.

Isn't there any way to constrain the variable so that it can only take on values of one particular type?

No. How would that help? Your program would just crash at a different point, when you associated that variable with a value of wrong type.

Scheme has something better, or at least more consistent with the design of the language: type predicates. The programmer can test any value to see whether it belongs to a particular data type by calling the type predicate for that data type and giving it the value in question as its operand.

Is there a type predicate for every data type?

There is one for every built-in type in Scheme:

If you design your own data types, you'll have to define your own type predicates for them.

Are the question marks part of the variables?

That's right. It's conventional in Scheme that variables whose values are predicates end in question marks.

What about integers? Is there a type predicate for them specifically, as opposed to numbers of any sort?

Yes. Each of the types of numbers recognized in the Scheme standard has a type predicate:

There procedures all have arity 1 and can accept an operand of any type.

The reason for distinguishing the nine type predicates in the main list is that they are mutually exclusive: If you give the same value as operand to all nine of them, you get back the ``true'' Boolean value no more than once.

Are they also jointly exhaustive? Do you always get back ``true'' from one or another of the nine type predicates?

That depends on your implementation of Scheme. Usually an implementation provides some objects that do not belong to any of the nine principal types.


Next topic
Previous topic
Table of contents


This document is available on the World Wide Web as

http://www.math.grin.edu/~stone/scheme-web/type-predicates.html


created July 1, 1995
last revised December 30, 1995

Copyright 1995 by John David Stone (stone@math.grin.edu)