% nacteni:
/* ['2.3_5.pl']. */

del1(A,[A|T],T).
del1(A,[H|T1],[H|T2]) :- del1(A,T1,T2).

insert(A,L,[A|L]).
insert(A,[H|T1],[H|T2]):- insert(A,T1,T2).

perm1([],[]).
perm1([H|T],L):- perm1(T,V), insert(H,V,L).

perm2([],[]).
perm2(L,[X|P]) :- del1(X,L,L1),perm2(L1,P).

perm3([],[]).
perm3(L,[H|T]):- append(A,[H|B],L),append(A,B,L1), perm3(L1,T).

% demonstracni vypis

  % abychom se vyhli varovanim "Redefined static procedure ..."
:- dynamic
       write_all_X/3,
       start/0.
       
write_all_X(Goal,X,Name):-
            call(Goal),write('  '),write(Name),write(' = '),write(X),nl,fail.
write_all_X(_,_,_).

start:- 
    write('Prace se seznamy - permutace'),nl,
    write('-------------------------------'),nl,
    write('perm1 napsany pomoci insert, vysledek volani "perm1([1,2,3],L)" :'), 
    nl, write_all_X(perm1([1,2,3],L), L, 'L'),nl,

    write('Pro blizsi porozumneni si vyzkousejte perm1, perm2 (reseny '), nl, 
    write('pomoci del1) a perm3 (s append) s trasovanim, napr. takto:'), nl,
    write('trace, perm1([1,2,3],L).'),nl,
    write('Pozn.: Po vypsani prvniho vysledku si dalsi vyzadate stisnutim ";"').
?-start.

:- retractall(write_all_X/3).
:- retractall(start/0).
