Subject: Re: divide_n

From: "Richard A. O'Keefe" <[email-masked]>
Date: Mon, 20 Nov 2000 15:53:17 +1300 (NZDT)

aikGuitarist <[email-masked]> wrote:
	
	I need help writing this prolog predicate:
	
Why?  I'm beginning to wonder if some of these might be homework problems,
in which case by far the best thing to do is to ask your tutor, teaching
assistant, lecturer, or whatever for some help.

	divide_n(list,n,A,B) that succeeds iff list is a List, n is an
	integer >= 0, and n is betwen 0 and length of list inclusive, A
	is a list containing the first P elements of List, and B is a
	list containing the other remaining elements of the list.

What is the relationship between P and n?

Using the Quintus Prolog library, I'd write

    :- use_module(library(length), [append_length/4]).

    divide_n(List, N, A, B) :-
	append_length(A, B, List, N).

which requires only that N be bound, _or_ that A be a proper list already,
_or_ that List be a proper list already.

Using only predicates that every Prolog system should already have:

    divide_n(List, N, A, B) :-
        length(A, N),
        append(A, B, List).
	
requires that N be bound _or_ that A be a proper list already,
and has the advantage of then being determinate.  However, if List is
a proper list and A, N are unbound, it will eventually undergo runaway
backtracking.  If List will be known, but N might not be,

    divide_n(List, N, A, B) :-
	append(A, B, List),
	length(A, N).

will give the right answers, but it will not be recognised as determinate
when N is known.  The slight trickiness of getting something that will work
in an many modes as possible is why library(length) exists in Quintus Prolog.