Subject: Re: [SWIPL] HELP : IMPLEMENTATION

From: "Richard A. O'Keefe" <[email-masked]>
Date: Mon, 19 Nov 2001 15:00:29 +1300 (NZDT)

"Vaithan Param" <[email-masked]> wrote:
	I have a real hard time implementing codes for these problems as
	I have just started working on prolog.  Can anyone of u , figure
	it out for me ? Appreciate it.

I must say that these sound suspiciously like homework problems.
The key point is to think declaratively.  Draw pictures.  Don't think
about DOING it, think about DESCRIBING it.

	allbutlast(X,L) if list X consists of all of list L except for its
	last element.  allbutlast(X,[]) should fail.
	Define allbutlast(X,L) (to find X given L).
	
The argument order here is unusual:  I would have expected L (the input)
to come first.

all_but_last(X, L) is true when X and L are lists and there is a one-
element list Y such that L = X ++ Y.

    all_but_last(X, L) :-
        append(X, [_], L).                           

	allbutmaybelast(X,L) if X consists of all of list L except for its
	last element if there is one.  (So allbutmaybelast([],[]) should
	succeed).Define allbutmaybelast(X,L) (to find X given L).
	
all_but_maybe_last(X, L) is true when X and L are lists and either
X = L = [] or there is a one-element list Y such that L = X ++ Y.
There are two cases: L = [], and L = [H|T].  In the latter case,
X = [H|R] for some R such that all_but_last(R, T).  So

    all_but_maybe_last([], []).
    all_but_maybe_last([H|X], [H|L]) :-
        all_but_last(X, L).
	
	threecopies(X,L) if list L consists of three copies of X appended
	together.Define threecopies(X,L) (to find L given X).
	For example the query threecopies([1,2],L) returns L=[1,2,1,2,1,2].
	
How do you append things?  Use append/3.  How do you append three copies?
Use append twice.  In Haskell:
	three_copies xs = xs ++ xs ++ xs
In Prolog:

    three_copies(X, L) :-
	append(X, T, L),
	append(X, X, T).

	even(L) if list L has an even number of elements.
	Define even(L).
	
There is a built-in predicate called length/2.
L has an even number of elements if and only if its length is divisible by 2.

    even_length(L) :-
	length(L, N),
	N mod 2 =:= 0.

	threeappend(X,Y,Z,L)  if L is the result of appending the lists X,Y and
	Z. Define threeappend(X,Y,Z,L).
	
See three_copies/2.
	
	Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp
	
Why would I want to do _THAT_?