Re: no char->string / string-append
- From: Neil Cerutti <leadvoice@xxxxxxxxx>
- Date: 30 Jan 2006 21:15:09 +0100
On 2006-01-27, Lauri Alanko <la@xxxxxx> wrote:
> In article <slrndtl450.1pc.leadvoice@xxxxxxxxxxxxxxxxxx>,
> Neil Cerutti <leadvoice@xxxxxxxxx> wrote:
>> I decided to build up a list after all, though I have to
>> reverse it at the end. I believe that's a scheme idiom, isn't
>> it?
>
> Yes, but in this case it's not necessary.
Ah, thanks for this prodding. I'd never have figured out
how to work from least significant digit up, otherwise.
>> Criticism is welcome. Particularly suggestions for splitting
>> it up into more digestible functions.
>
> Your function is too complex, in the sense that it does too
> much work to get to the result. And it is too simple, in that
> it doesn't treat all cases correctly: what if number is zero?
If the number is zero it seems to have worked OK, returning (0)
as expected.
(convert 0 12) --> (0)
(convert 0 2) --> (0)
> Hints: you don't need the power function. You don't need to
> reverse anything. You do need the modulo function.
Thanks for the tips.
Here's V0.2:
; Convert [ number:Integer base:Integer ] -> List
; Convert number into a List representation of a number in base. Traditional
; hexadecimal digits are not used. Bases less than 2 cause the function to
; return #f. The intent is that the result can be easily translated into a
; notation of your choice.
; (convert 10 2) --> (1 0 1 0)
; (convert -20 4) --> (- 1 1 0)
; (convert 100 17) --> (5 15)
(define (convert number base)
(if (< base 2)
#f
(let loop ((n (abs number))
(result '()))
(if (< n base)
(if (negative? number)
(cons '- (cons n result))
(cons n result))
(loop (quotient n base) (cons (modulo n base) result))))))
It was with some consternation that I discovered my first attempt
at this new procedure would have listed the digits in reverse.
--
Neil Cerutti
.
- References:
- no char->string / string-append
- From: Neil Cerutti
- Re: no char->string / string-append
- From: Lauri Alanko
- Re: no char->string / string-append
- From: Neil Cerutti
- Re: no char->string / string-append
- From: Lauri Alanko
- no char->string / string-append
- Prev by Date: Re: arrays vs. vectors
- Next by Date: Re: interactive scheme
- Previous by thread: Re: no char->string / string-append
- Next by thread: Metaprogramming using Scheme
- Index(es):
Relevant Pages
|