[plt-scheme] Cost of string creation? / Euler 8 code review

From: Grant Rettke (grettke at acm.org)
Date: Mon Jul 2 21:56:29 EDT 2007

Hi folks,

I wrote a solution for project Euler #8:


My solution involves what I would imagine to be a decent amount of
string creation: 5000 strings. Usually string creation makes programs
slow but this doesn't run slowly at all, it runs very fast, faster
than a lot of the other solutions posted.

The creation is like this:
1. get a substring of a string
2. convert it to a list of chars
3. convert each char to a string
3. convert each string to a number

Why isn't this an expensive operation?

Here is my solution if that helps or if you would be kind enough to
code review this:

$LastChangedDate: 2007-07-02 20:22:48 -0500 (Mon, 02 Jul 2007) $
$LastChangedRevision: 271 $
$HeadURL: svn://osiris/project_euler/trunk/euler8.ss $
(module euler8 mzscheme

  (provide (all-defined))

  (require (prefix ri13: (lib "13.ss" "srfi")))

  (define the-number

  ;! Get the greatest product of consecutive digits in a number
  ;  string -> int -> int
  ; .example (grtprod "1234" 2) -> 12
  ; .pre-condition length of str >= the consecutive digit number
  ; .parameter str string: The value being checked
  ; .parameter dgts int: The number of consecutive digits to analyze
  ; .post-condition none
  ; .returns int:
  (define greatprod1
    (λ (str digits)
      (let* ([len (string-length str)]
             [stop (add1 (- len digits))])
        (let loop ([start 0] [end digits] [found 0])
          (if (= start stop) found
              (let* ([candidate (apply * (map string->number (map
string (ri13:string-fold cons '() (ri13:substring/shared str start
                    [next-start (add1 start)]
                    [next-end (+ next-start digits)])
                 (if (> candidate found) candidate found)))))))))

Posted on the users mailing list.