[plt-scheme] iterate over characters in string

From: Chris Uzdavinis (chris at atdesk.com)
Date: Tue Aug 13 10:46:08 EDT 2002

MJ Ray <markj at cloaked.freeserve.co.uk> writes:

>   For list-related administrative tasks:
>     http://list.cs.brown.edu/mailman/listinfo/plt-scheme
> Chris Uzdavinis <chris at atdesk.com> wrote:
> >   * is there any kind of for-each function that works on a string at
> >     the byte level?
> What about map?

That would work as well as for-each on a normal list, but I'm looking
for a function that operates *directly* on a string without having to
convert it into a list first.

> > It seems a bit verbose (for my taste) and possibly inefficient due to
> > calling string->list if it really is O(n).
> Can any iteration over a list be anything other than O(n)?

Of course not.  But I'm really wanting to avoid O(2n) when O(1n) will
do.  It shouldn't be necessary to traverse twice... once to
convert the string to a list, and again to traverse the list itself.

A null terminated string is in a format that is directly traversable
without needing to be transformed into any other representation.
Well, that is true unless DrScheme doesn't implement such
functionality.  But it could.

> > I'm hoping some mechanism does exist that I just overlooked.  Ideally
> > I'd do something like this: 
>    (define (calc-checksum line)
>      (let ((ck 0))
>        (map (lambda (c) (set! ck (+ ck (char->integer c))))
>             (string->list line))
>        (modulo ck 256)))

Thanks, but the point of my question was how to get around having to
call string->list and still iterate over the characters.  What you
provided is correct but it's still doing the same amount of work as my
original code does.


Posted on the users mailing list.