[plt-scheme] iterate over characters in string

From: ptg at ccs.neu.edu (ptg at ccs.neu.edu)
Date: Tue Aug 13 10:52:24 EDT 2002

Chris, here's a fairly non-verbose version:

  ; : str -> nat
  (define (checksum line)
    (modulo (apply + (map char->integer (string->list line))) 256))

For practice, see if you can write one using the foldl function instead
of map and apply.  If the intermediate list bothers you, either look up
string-ref, or implement a deforestation compiler pass for mzscheme :-)

The best way to good performance is to implement a handful of versions
and benchmark them.  DrScheme's profiler will help.


At Tue, 13 Aug 2002 14:23:03 GMT, MJ Ray wrote:
> 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?
> > 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)?
> > 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)))

Posted on the users mailing list.