mymember(X,[X|_]).
mymember(X,[_|Y]) :- mymember(X,Y).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

myappend([],A,A).
myappend([X|Y],Z,[X|W]) :- myappend(Y,Z,W).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

rappend([X|Y],Z,[X|W]) :- rappend(Y,Z,W).
rappend([],A,A).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xlength([],0).
xlength([_|Y],N) :- xlength(Y,N-1).

mylength([],0).
mylength([_|Y],N) :- mylength(Y,M), N is M+1.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Implementing Length with an accumulator


mylen2(L,N) :- lenacc(L,0,N).

% This is the base case.  It serves to move the
% accumulator value (argument 2) into the answer argument
% (argument 3) at the end of computation (i.e., when
% we reach the empty list.)

lenacc([],N,N).

lenacc([H|T],A,N) :- A1 is A+1, lenacc(T,A1,N).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


swap_first_two([X,Y|Rest],[Y,X|Rest]).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

list_elem(L,E,N) :- all_elem(L,E),length(L,N).

all_elem([],_).
all_elem([E|R],E) :- all_elem(R,E).



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

factorial(0,1).

%precondition X is greater or equal to zero
factorial(X,Y) :- W is X-1,
                  factorial(W,Z),
                  Y is Z*X.


%Note here that the multiplication subgoal has to occur
%AFTER the recursive call since the recursive call determins
% the value of Z.  So...Z gets computed on the way down and
% Y gets computed as we pop out of each recursive all.
%  Using an accumulator will avoid this.

%% Factorial using an accumulator

% this is the base case.  It also serves to transfer
% the result from the accumulator (argument 2) into the 
% result argument (argument 3)

factorial2(0,N,N).

%precondition:  A is 1 initially

factorial2(N,A,F) :-
   N > 0,
   A1 is N*A,
   N1 is N -1,
   factorial2(N1,A1,F).

% The accumulator for the factorial has to be 1 initially
% since things are being multiplied with it and since the
% factorial of 0 is 1.
%
% E.g., factorial2(3,1,N) or factorial(5,1,N)
% are example calls.
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

sumlist([],0).

sumlist([X|Rest],Ans) :- sumlist(Rest,Partial),
                         Ans is Partial+X.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
