问题
While trying to write a solution to the longest common sublist problem in Scheme, I'm having trouble figuring out what is wrong with what I have so far. I think it's the right idea and before worrying about polynomial time I'm just trying to get one that works at all. I haven't written in a functional language before and the syntactic differences can make things a little harder at first.
(define (lcs lst1 lst2)
(if (or (null? lst1) (null? lst2)) '()
(if (not (null? lcs)) lcs
(if (equal? (car lst1) (car lst2))
(cons (car lst1))(lcs (cdr lst1) (cdr lst2)))
(let ((a (lcs (cdr lst1) lst2))
(b (lcs lst1 (cdr lst2))))
(if (> (cadr a) (cadr b)) a b)))))
Is this on the right track? What's wrong with it? Any help is appreciated, thank you.
回答1:
(if (not (null? lcs)) lcs
Here you're checking whether lcs
(which is a function) is the empty list. If it isn't (which is always the case because a function is not a list), you return the function itself.
I assume what you meant to do was to call the function lcs
and check whether the result was the empty list. To call a function, you need to surround the function in parentheses. Further if the function takes arguments (which lcs
does), you need to specify those arguments when calling the function.
It is not clear to me what this if
is supposed to accomplish and as far as I can tell, there's no need for it, so just remove it.
(if (> (cadr a) (cadr b)) a b)
cadr
returns the second element of a list, so here you're returning the list whose second element is greater. Given that your goal is to find the longest sublist, this makes no sense. You should be returning the list whose length is greater. To do this replace the condition with
(> (length a) (length b))
In addition to those logic errors, you have a small syntax error:
(cons (car lst1)) (lcs (cdr lst1) (cdr lst2)))
Here you're calling cons
with one argument (which is an error) and then calling (lcs (cdr lst1) (cdr lst2))
as the else-part of the list. Since you obviously intended (lcs (cdr lst1) (cdr lst2))
to be the second argument to cons
, just remove the second closing paren after car lst1
.
来源:https://stackoverflow.com/questions/4119677/longest-common-sublist