I try to use Scheme to implement LCS algorithm, but there is a bug.
(define X (list #\A #\B #\C #\B #\D #\A #\B))
(define Y (list #\B #\D #\C #\A #\B #\A))
(define prefix (lambda (i s) (if (= i 0) '() (cons (car s) (prefix (- i 1) (cdr s))))))
(define (pick ith s) (if (= ith 1) (car s) (pick (- ith 1) (cdr s))))
(define (LCS x y) (define (optimal i j) (cond ((or (= i 0) (= j 0)) 0) ((eq? (pick i x) (pick j y)) (+ 1 (optimal (- i 1) (- j 1)))) (else (max (LCS (prefix (- i 1) x) y) (LCS x (prefix (- j 1) y)))))) (optimal (length x) (length y)))
1 ]=> (load "lcs.scm")
;Loading "lcs.scm"... done ;Value: lcs
1 ]=> (lcs X Y)
;Value: 5
The result should be 4, I do not know where is the bug.