Levenshtein Distance

The Levenshtein distance between two strings a and b can be computed using the following algorithm:

      (define (distance a b)
        (define (d i j)
          (cond ((= i 0)
                 j)
                ((= j 0)
                 i)
                ((char=? (string-ref a (- i 1))
                         (string-ref b (- j 1)))
                 (min (+ 1 (d (- i 1) j))
                      (+ 1 (d i (- j 1)))
                      (d (- i 1) (- j 1))))
                (else
                 (min (+ 1 (d (- i 1) j))
                      (+ 1 (d i (- j 1)))
                      (+ 1 (d (- i 1) (- j 1)))))))
        (d (string-length a) (string-length b)))

If the last characters of the prefixes are not the same, then the distance between the prefixes is calculated just as though their last characters were the same, except we'll need a substitution at the last character when reducing the problem to computing the distance between the prefixes without their last characters. That adds one operation, which explains the one difference seen in the code for that situation.