* Re: call-with-values and primitives
2013-01-11 14:23 call-with-values and primitives bromley
@ 2013-01-11 15:43 ` Ian Price
2013-01-11 16:56 ` Andy Wingo
1 sibling, 0 replies; 3+ messages in thread
From: Ian Price @ 2013-01-11 15:43 UTC (permalink / raw)
To: bromley; +Cc: guile-user
bromley@lavabit.com writes:
> Hello.
>
> Why does it return -1? Could anyone explain?
> (Comments are mine.)
The general principle is to try and give sensible results when +,*,etc
are called with a number of arguments other than 2. By thinking them
through at this level you can, in theory, write more general code and
have it "just work". Not only does it apply to various functions, but it
is generally considered a sensible macro design principle too, as in the
case of, among others, 'and' and 'or'.
>
> (call-with-values (lambda () (values 4 5))
> (lambda (a b) b)) ; a is 4 and b is 5; return 5
> ⇒ 5
>
> (call-with-values * -)
> ⇒ -1
If you call * with 0 arguments, it returns one value, the number 1. This
makes some sense since 1 is the identity for multiplication.
i.e. (* 1 x) = x = (* x 1) for all x
If you call - with one argument, it negates that argument, as if you had
done (- 0 x).
Putting both of these together, (call-with-values * -) is equivalent to (- (*))
scheme@(guile−user)> (*)
$2 = 1
scheme@(guile−user)> (- 1)
$3 = −1
scheme@(guile−user)> (- (*))
$4 = −1
> (call-with-values + +)
> 0
Similarly to multiplication, if you call (+) with one argument, you get
the identity for +, which is 0. This expression then, is equivalent to
(+ (+)) = (+ 0) = 0
> (call-with-values + -)
> 0
Similar to the above situation, you can think of this as being
equivalent to (- (+)). Negating 0, naturally enough, gives you 0.
scheme@(guile−user)> (+)
$5 = 0
scheme@(guile−user)> (- (+))
$6 = 0
> (call-with-values - -)
> ERROR: Wrong number of arguments to -
While we extend / and - to have sensible results for the one argument
case (reciprocal and negation), and we extend it for more than two
arguments, there is not an identity for / or - [0], so we mark the zero
argument case as errors for both.
scheme@(guile−user)> (/)
ERROR: In procedure /:
ERROR: Wrong number of arguments to /
scheme@(guile−user)> (-)
ERROR: In procedure −:
ERROR: Wrong number of arguments to −
[0] Well, more correctly, they have right identities, of 1 and 0
respectively, but no left ones
--
Ian Price -- shift-reset.com
"Programming is like pinball. The reward for doing it well is
the opportunity to do it again" - from "The Wizardy Compiled"
^ permalink raw reply [flat|nested] 3+ messages in thread