ಠ_ಠ
ಠ_ಠ

Reputation: 3078

How does addition work in racket/scheme?

For example, if you try (+ 3 4), how is it broken down and calculated in the source, specifically? Does it use recursion with add1?

Upvotes: 3

Views: 1425

Answers (2)

Asumu Takikawa
Asumu Takikawa

Reputation: 8523

The implementation of + is actually much more complicated than you might expect, because arithmetic is generic in Racket: it works on integers, rational numbers, complex numbers, and so on. You can even mix and match these kinds of numbers and it'll do the right thing. In the end, it's ultimately going to use arithmetic in C, which is what the runtime system is written in.

If you're curious, you can find more of the guts of the numeric tower here: https://github.com/plt/racket/blob/master/src/racket/src/numarith.c

Other pointers: Bignum arithmetic, the Scheme numeric tower, the Racket reference on numbers.

Upvotes: 8

Óscar López
Óscar López

Reputation: 235994

The + operator is a primitive operation, part of the core language. For efficiency reasons, it wouldn't make much sense to implement it as a recursive procedure.

Upvotes: 7

Related Questions