Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do + and * evaluate to 0 and 1 respectively?

Tags:

lisp

scheme

I'm using GNU/MIT Scheme:

1 ]=> (+)

;Value: 0

1 ]=> (*)

;Value: 1

1 ]=> (-)

;The procedure #[arity-dispatched-procedure 2] has been called with 0 arguments; it requires at least 1 argument.
;To continue, call RESTART with an option number:
; (RESTART 1) => Return to read-eval-print level 1.

2 error> (/)

;The procedure #[arity-dispatched-procedure 3] has been called with 0 arguments; it requires at least 1 argument.
;To continue, call RESTART with an option number:
; (RESTART 2) => Return to read-eval-print level 2.
; (RESTART 1) => Return to read-eval-print level 1.

How come + and * are both evaluated to 0 and 1 respectively. And why evaluating - and / throws an error?

Is this part of the Scheme definition or is it an implementation detail in GNU/MIT Scheme?

like image 497
rahmu Avatar asked Dec 18 '13 16:12

rahmu


2 Answers

The reasoning behind this is that + and * have identity elements

1 * x = x * 1 = x
0 + x = x + 0 = x

While - and / have right identities, but as left associative operators this negates (pun!) their value. It makes sense to think about a variadic plus as a fold over a list of numbers with the initial element being an identity since mathematically, you can't differentiate this from just adding them together one by one. Furthermore, a fold over an empty list is just that seed element, the identity.

However since - and / lack identity elements, there is no sane default to return.

And it is a part of R5RS

like image 188
Daniel Gratzer Avatar answered Sep 28 '22 02:09

Daniel Gratzer


If you think of + or * in terms of a fold, or reduce you'll see they need a seed or accumulator value. For *, 1 makes sense. For + 0 makes sense. So you are getting back the seed/accumulator of a reduce.

It's also part of the spec. http://gnuvola.org/software/guile/doc/Arithmetic.html#index-g_t_002a-487

like image 33
Mark Bolusmjak Avatar answered Sep 28 '22 01:09

Mark Bolusmjak