|
Home
>
2. program control
>
2.1 multi-value binds
>
2.1.1 How are local multi-value-bind's done in Common Lisp and Dylan?
|
Previous
Next
|
|
|
|
|
|
Dave Moon
|
These are equivalent Common Lisp and Dylan program fragments:
[Common Lisp]
(multiple-value-bind (a b c) (f x)
(g a b c))
[Dylan]
let (a,b,c) = f(x);
g(a,b,c);
|
|
Peter Norvig
in
|
Quote from his textbook Paradigms of "Artificial Programming":
Sometimes we want a single function to return more than one piece of
information. Of course, we can do that by making up a list or structure
to hold the information, but then we have to go to the trouble of defining
the structure, building an instance each time, and then taking that
instance apart to look at the pieces.
Consider the function round. One way it can be used is to round off a
floating-point number to the nearest integer. So (round 5.1) is 5.
Sometimes, though not always, the programmer is also interested in
the fractional part. The function round serves both interested and
disinterested programmers by returning two values: the rounded integer
and the remaining fraction:
(round 5.1) => 5 .1
There are two values after the => because round returns two values.
Most of the time,
multiple values are ignored, and only the first value is used. So (* 2
(round 5.1)) is 10, just as if round had only returned a single value. If you
want to get at multiple values, you have to use a special form, such as
multiple-value-bi nd:
(defun show-both (x)
(multiple-value-bind (int rem)
(round x)
(format t "~f = ~d + ~f" x int rem)))
> (show-both 5.1) 5.1 = 5 + 0.1
|
|
fun-principal
|
type into the Dylan interactor:
The round method is part of Dylan's
define method say-rounding-values ( x :: <real> )
let ( integer, remainder ) = round(x);
format-out( "\n %= = %d + %= \n\n",
x , integer, remainder );
end;
=> No values
say-rounding-values (5.1);
=> No values
Annotation about the Dylan interactor:
The dylan interactor return results via constant bindings (readonly
bindings), which means within the playground the results can be reused
via their binding name. Playground results are named via an integer
which is prefixed by a dollar-sign. This reflect the Dylan convention to
prefix module constant bindings (readonly bindungs). So the playground
writes internal something like
define constant $0 = result item
In case of multiple return values each value get associated to a constant
binding.
Annotation about say-rounding-values
The call of say-rounding-values the method format-out
opens a command window as outwindow, but note that format-out might
buffer its content until it reaches a linebreak, \n. So if nothing is print in
the output window make sure your output string ends with a linebreak.
Output window
|
|
|
|
|
|