# Class 41: Multiple-Valued Procedures

Back to Variable-Arity Procedures. On to Discussion of Exam 2.

Held Friday, November 15, 2002

Summary

Today we consider why and how to return more than one value from a procedure.

Due

• Exam 2.

Assignments

Notes

• No reading this weekend! We'll spend Monday going over the exam.
• No lab today! We'll take a discussion-oriented approach to today's key problems.
• Have a great weekend.

Overview

• Why return multiple values from procedures
• How to return multiple values from procedures
• What to do with those multiple values
• An alternative

## Returning Multiple Values

• As you write more and more procedures, you will find that you occassionally write procedures that naturally return more than one value.
• Although a list contains many values, you should think of procedures that return a list as returning the list as a value.
• For example,
• When you divide an integer by another integer, you end up with the result and a possible remainder.
• Similarly, you can split a real number into a whole part and a fractional part.
• You might want to split a list into two parts: those that meet a predicate and those that don't meet a predicate.
• You might want to tally more than one thing at once (e.g., A's, B's, and C's in a list of grades).
• In Scheme, you can use `values` to return more than one value from a procedure.
• The values returned are literally separate values; they're not a list.
• However, it's not all that useful to return multiple values unless you can do something with them.
• The `call-with-values` procedure takes two parameters, a zero-parameter procedure, genproc, that returns multiple values and a procedure, proc, of the same number of parameters. It evaluates genproc and applies proc to the result.
• For example,
```> (values 1 2)
1
2
> (call-with-values (lambda () (values 1 2)) +)
3
> (call-with-values (lambda () (values 1 2 3 4))
2
```
• Are there alternatives? Certainly. You could simply construct a list whenever you want to return multiple values and then destruct the list when you want to extract values.
• Many consider the use of lists in this case inelegant.

## History

Thursday, 29 August 2002

Back to Variable-Arity Procedures. On to Discussion of Exam 2.

Disclaimer: I usually create these pages on the fly, which means that I rarely proofread them and they may contain bad grammar and incorrect details. It also means that I tend to update them regularly (see the history for more details). Feel free to contact me with any suggestions for changes.

This document was generated by Siteweaver on Mon Dec 2 08:41:56 2002.
The source to the document was last modified on Tue Sep 3 23:13:33 2002.
This document may be found at `http://www.cs.grinnell.edu/~rebelsky/Courses/CS151/2002F/Outlines/outline.41.html`.

You may wish to validate this document's HTML ; ; Check with Bobby

Samuel A. Rebelsky, rebelsky@grinnell.edu