Search code examples
listschemecons

Concatenating list elements - Scheme


If i have a scheme code that generates the following result: (i'm using cons)

'((1 . 0) . 0)

How can i take this, and just simply display 100 as if it were just one integer number and not a list presented with those dots and parenthesis?

Thanks!

EDIT:

my full code:

(define (func X) 
    (if ( <= X 3 )
       X
            (cons (modulo X 4) (func(floor(/ X 4)) ))  
))

Solution

  • If I understand correctly, you're trying to convert a number from base 10 to base 4, and then display it as a number, but there are several problems with your implementation.

    You're building a list as output - but that's not what you want, you want a number. Also, you're traversing the input in the wrong order, and that's not the correct way to find the quotient between two numbers. Perhaps this will help:

    (define (func X)
      (let loop ((n X) (acc 0) (mult 1))
        (if (< n 4)
            (+ (* mult n) acc)
            (loop (quotient n 4)
                  (+ (* mult (modulo n 4)) acc)
                  (* mult 10)))))
    

    Alternatively, you could output a string to stress the fact that the output is not in base 10:

    (define (func X)
      (let loop ((n X) (acc ""))
        (if (< n 4)
            (string-append (number->string n) acc)
            (loop (quotient n 4)
                  (string-append (number->string (modulo n 4)) acc)))))
    

    It'll work as expected:

    (func 16)
    => 100