## [SICP 2.1.3] Exercise 2.5 Memo

Exercise 2.5- Show that we can represent pairs of nonnegative integers using only numbers and arithmetic operations if we represent the pair a and b as the integer that is the product 2^a3^b. Give the corresponding definitions of the procedures cons, car, and cdr.

So far, we’ve seen an implementation of these procedures using lambda expression. By the way, it seems that we can implement them with only numbers and some arithmetic operations according to the problem, so let’s create that version of the procedures.

First of all, We need a procedure that tells us the power of 2 and 3 from a value.

```(define (find-times-of-n n x)
(define (iter dev-x result)
(let ((r (remainder dev-x n)))
(if (= r 0) (iter (/ dev-x n) (+ result 1))
result)))
(iter x 0))
```

What we have to do for getting the power of n( in this case, 2 or 3 would be passed ) from value x is only devide n from x until the remainder of the value / n is non-zero.

Next, we’ll create procedure cons. This is easy because we only need to create a procedure that takes two arguments ( a and b ), and returns 2^a3^b. The procedure will be as follows:

```
(define (pow x n)
(define (iter i result)
(if (= i n) result (iter (+ i 1) (* result x))))
(iter 0 1))

(define (cons x y) (* (pow 2 x) (pow 3 y)))

```

Finally, we’ll create procedure car and cdr. Let’s use the procedure find-times-of-n:

```
(define (car cons) (find-times-of-n 2 cons))
(define (cdr cons) (find-times-of-n 3 cons))

```

If we want to get the output, you can implement the procedure like this:

```
(define (print-cons cons)
(newline)
(display "(")
(display (car cons))
(display ",")
(display (cdr cons))
(display ")"))

(define hoge (cons 61 22))
(print-cons hoge) ; (61, 22)

```

<<

Top

>>