%%% 14.11.2009 %%%
% Group 1

%% Task 1
% is_member(E, L) :- checks if E is element of L
is_member(X, [X|_]).
is_member(X, [_|T]) :- is_member(X, T).

% list_length(L, N) :- Finds the length N of the list L
list_length([], 0).
list_length([_|T], N) :- list_length(T, N1), N is N1 + 1.

% elements_sum(L, S) :- S is the sum of all elements of the list L
elements_sum([], 0).
elements_sum([H|T], S) :- elements_sum(T, S1), S is S1 + H.

% even(X) :- checks if X is even
even(0).
even(X) :- 0 is X mod 2.

% append_lists(A, B, C) :- C is the result of appending A and B
append_lists([], B, B).
append_lists([H|T], B, [H|C]) :- append_lists(T, B, C).

% reverse_list(L, R) :- R is the reverse list of L
reverse_list([], []).
reverse_list([H|T], R) :- reverse_list(T, R1), append_lists(R1, [H], R).

% head(H, L) :- H is the head of the list L
head(H, [H|_]).

% last_element(E, L) :- E is the last element of L
% L is a list of list of numbers
last_element(E, L) :- reverse_list(L, R), head(E, R).

% remove_element(E, L, M) :- M is the result of removing one appearance of E from L
remove_element(E, [E|T], T).
remove_element(E, [H|T], [H|S]) :- remove_element(E, T, S).

% is_perm(L, M) :- Checks if L is a permutation of M
is_perm([], []).
is_perm([H|T], M) :- is_member(H, M), remove_element(H, M, N), is_perm(T, N).

% is_concatenation(X, A, B) :- Checks if X is result of concatenating A and B
% X, A, B - sets
is_concatenation(X, A, B) :- append_lists(A, B, Y), is_perm(Y, X).

% first_condition(X, Y)
first_condition(X, Y) :- is_member(A, Y),
						 is_member(B, Y), A \= B,
						 is_concatenation(X, A, B).

% second_condition(X)
second_condition(X) :- list_length(X, N), even(N).

% third_condition(X, Y)
third_condition(X, Y) :- elements_sum(X, S),
						 last_element(Last, Y),
						 last_element(S, Last).

% p(X, Y) :- main task
% X is a list of numbers, Y is a list of lists of numbers.
p(X, Y) :- first_condition(X, Y),
		   second_condition(X),
		   third_condition(X, Y).