Re: Sublists question

From: Bill Spight (Xbspight_at_pacbell.net)
Date: 03/25/04


Date: Thu, 25 Mar 2004 17:16:24 GMT

Dear zeus,

> What I intend to do in the 3 generate lists prdeicates is this:
> for N=1, I=3 generate the list [1,_,1,_,1]

I see a problem. 'I' is the size of the list. So you should have I = 5,
not I = 3.

> which at the end of the
> recursion when I=0 will be tested to be sublist of L

I = 0? Why would you decrease the size of the list? Are you building a
list from its sublists?

OK, I think I see what you are up to. Let's clean the predicate up by
eliminating the sublist test.

generate_list(_,0,_).
    
% responsible for placing the Ns in the sublist
generate_list(N,I,List) :-
    I>0,
    II is I-1,
    NNN is N+1,
    III is II mod NNN,
    III is 0,
    generate_list(N,II,[N|List]).

What you are doing here is building a list from the bottom, by adding N
*before* it. That's OK if you call generate_list/3 like this:
generate_list(N,Size,[]), with the empty list. But then how do you
return the eventual list that you have built? You need another variable
for that: generate_list(N,Size,[],List).

You can do it that way, but I think what you want to do is build the
list from left to right. Here's how to do that.

generat_list(_,0,[]).

A list of length 0 is empty.

generate_list(N,I,[Head|Tail]) :-
    I>0,
    II is I-1,
    NNN is N+1,
    III is II mod NNN,
    III is 0,
    Head = N,
    generate_list(N,II,Tail).

% responsible for placing the variables in the sublist
generate_list(N,I,[_|Tail]) :-
    I>0,
    II is I-1,
    generate_list(N,II,Tail).

In the one case, the head of the list is N, in the other, it is
undetermined.

Note that you have a dependency in the clauses. The third clause assumes
that the second has failed. Often that's the way to go, for practical
reasons, to avoid unnecessary tests inside a loop. But you should be
aware that you are getting away from a logical reading of the predicate.

This still may not work, but I think it's closer to what you want to do.
:-)

Good luck!

Bill



Relevant Pages

  • Re: Sublists question
    ... > I'm afraid I led you a bit astray with that. ... %recursively generate all sublists ... II is I-1, ... % responsible for placing the variables in the sublist ...
    (comp.lang.prolog)
  • Re: Sublists question
    ... and now it compiles and even finds the langford sequence for ... > %recursively generate all sublists ... > II is I-1, ... > % responsible for placing the variables in the sublist ...
    (comp.lang.prolog)
  • Re: longest decreasing subsequence?
    ... > Now I'm scratching my head wondering if there's a better way than ... > enumerating all decreasing sublists of the input and returning the ...
    (comp.lang.prolog)