% INTRODUCTION

animal(elephant).

bigger(elephant, bird).
bigger(elephant, cow).
bigger(cow, mouse).

bigger(X, Y) :-
    bigger(X, A), bigger(A, Y).

% Note: The above definition for a transitive relation
% results in loop, which wasn't resolved during the tutorial.
% If you want to know more about it, take a look at this answer:
% https://stackoverflow.com/a/28615704


% SIMPLE LIST TASKS
% inspired from http://www.ic.unicamp.br/~meidanis/courses/mc336/2009s2/prolog/problemas/

getfirst([X|_], X).

getlast([X], X).
getlast([_|R], X) :-
    getlast(R, X).

getsecondlast([X,_], X).
getsecondlast([_|R], X) :-
    getsecondlast(R, X).

getlength([], 0).
getlength([X|R], L) :-
    getlength(R, N), L is N+1.

second([], []).
second([X], [X]).
second([X,Y|R], [X|S]) :-
    second(R, S).

fourth(X, Y) :-
    second(X, Z), second(Z, Y).

prepend(X,SomeList,[X|SomeList]).

duplicate([], []).
duplicate([X|R], [X,X|S]) :-
    duplicate(R, S).


% INSERTION SORT

insert(X, [], [X]).
insert(X, [H|R], [H|S]) :-
    X >= H, insert(X, R, S).
insert(X, [H|R], [X,H|R]) :-
    X =< H.

inssort([], []).
inssort([H|T], L) :-
    inssort(T, TSorted),
    write('inserting '),
    write(H),
    write('\n'),
    insert(H, TSorted, L).