So, I've ran into this problem where I've been trying to code a means to convert a binary number to a string in Scheme (R5RS), but I've been having some....problems. My tutor and I tried to solve it over the course of an hour, but we haven't been able to solve it.
In fact, as of the time I finished the last session, he left behind the following:
(define binary->string (lambda (lst)
(define str (make-string 0))
(letrec ((recurse (lambda (l)
; turn into not null
(if (null? l)
(lambda ()
(set! str (string-append str (number->string (car l))))
(recurse (cdr l)))
)
)
)
)
(recurse lst)
)
str)
)
(binary->string '(0 1 0 1 0 0 1 1))
See where it says "turn into not null"? Well, we've had some problems trying to convert the number into not null. I sure hope this helps. Thanks!
CodePudding user response:
So you want this result?
> (binary->string '(0 1 0 1 0 0 1 1))
"01010011"
I see you've already used string-append
and number->string
, so you should also use apply
and map
:
(define (binary->string arg)
(apply string-append
(map number->string arg)))
> (binary->string '(0 1 0 1 0 0 1 1))
"01010011"
If you also want to convert it into decimal number, use string->number
with radix 2:
> (string->number "01010011" 2)
83