:-use_module(library(clpfd)).


% N is the dot product of lists V1 and V2.
dot(V1, V2, N) :- maplist(product,V1,V2,P), sumlist(P,N).
product(N1,N2,N3) :- N3 is N1*N2.

% Matrix multiplication with matrices represented
% as lists of lists. M3 is the product of M1 and M2
mmult(M1, M2, M3) :- transpose(M2,MT), maplist(mm_helper(MT), M1, M3).
mm_helper(M2, I1, M3) :- maplist(dot(I1), M2, M3).




suml([],[],[]).

suml(L1,L2,[N|R2]):-
    L1 = [E1|T1],
    L2 = [E2|T2],
    N is E1 + E2,
    suml(T1,T2,R2).



summ([],[],[]).
summ(M1,M2,[Lr|R2]):-
    M1 = [E1|T1],
    M2 = [E2|T2],
    suml(E1,E2,Lr),
    summ(T1,T2,R2).



flatten(List, Flattened):-
  flatten(List, [], Flattened).

flatten([], Flattened, Flattened).
flatten([Item|Tail], L, Flattened):-
  flatten(Item, L1, Flattened),
  flatten(Tail, L, L1).
flatten(Item, Flattened, [Item|Flattened]):-
  \+ is_list(Item).

touspositifs(X):-
    flatten(X,XF),
    tp(XF).

tp([]).
tp(X):-
    X = [E|L],
    E #>= 0,
    tp(L).
    
