Reputation: 542
I'm having a bit of trouble implementing this program in Scheme, although I think I'm 90% of the way there. Unfortunately I need to be a little vague about it since this is a homework assignment.
I need to take one list as input, generate all possible subsequences of the list, and return ONE that matches a certain criteria. I have finished the code to generate all subsequences of the list and also to tell if a certain subset is a solution. I am however having trouble having Scheme return that solution. My code basically looks like this right now
(define (function rest_of_list subsequence)
(if (subsequence is a solution) subsequence)
(if (> (length rest_of_list) 0) (function (cdr rest_of_list) (append subsequence (car rest_of_list))))
(if (> (length rest_of_list) 0) (function (cdr rest_of_list) subsequence)))
What this code should do is for each element in the list, it branches recursively in two directions. In one direction it adds (car rest_of_list) to subsequence and continues down the list. In the other direction it ignores (car rest_of_list) and continues down the list. As soon as it finds a subsequence that is acceptable, it returns it and that is the result of the function called function. Right now I just get blank output. And I sort of understand why I guess, but not well enough to fix this.
Upvotes: 1
Views: 211
Reputation: 236004
It's a bit tricky without looking at the exact details of your implementation, but I'd do something along these lines:
(define (function rest_of_list subsequence)
(cond ((null? rest_of_list)
'())
((subsequence is a solution)
subsequence)
(else
(combine (function (cdr rest_of_list) (append subsequence (car rest_of_list)))
(function (cdr rest_of_list) subsequence)))))
The interesting part is how you combine
both branches, it could be as simple as a cons
. Also notice that a base case is probably missing: what happens if the rest of the list is null?
Upvotes: 1