[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: call-with-values and primitives
From: |
Ian Price |
Subject: |
Re: call-with-values and primitives |
Date: |
Fri, 11 Jan 2013 15:43:11 +0000 |
User-agent: |
Gnus/5.13 (Gnus v5.13) Emacs/23.3 (gnu/linux) |
address@hidden 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"