:- use_module(library(lists)).
mm0([S,E,N,D,M,O,R,Y]) :-
     generate0([S,E,N,D,M,O,R,Y]),      % generate
     S>0, M >0,                         % test
     alldiff([S,E,N,D,M,O,R,Y]),        % test
     test_sum(S,E,N,D,M,O,R,Y).         % test
generate0([]).
generate0([X|Xs]):-
    digit(X),
    generate0(Xs).
digit(0).
digit(1).
digit(2).
digit(3).
digit(4).
digit(5).
digit(6).
digit(7).
digit(8).
digit(9).

mm1([S,E,N,D,M,O,R,Y]) :-
     generate1([S,E,N,D,M,O,R,Y]),      % generate
     S>0, M >0,                         % test
     alldiff([S,E,N,D,M,O,R,Y]),        % test
     test_sum(S,E,N,D,M,O,R,Y).         % test

test_sum(S, E, N, D, M, O, R, Y) :-
     V1 is             1000*S + 100*E + 10*N + D 
          +            1000*M + 100*O + 10*R + E,
     V2 is 10000*M + 1000*O + 100*N + 10*E + Y,
     V1 = V2.
generate1([]).
generate1([X|Xs]):-
    member(X,[0,1,2,3,4,5,6,7,8,9]),
    generate1(Xs).

alldiff([]).

alldiff([X|L]):-
    diff(X,L),
    alldiff(L).
diff(X,[]).
diff(X,[V|L]):-
     X \= V,
     diff(X,L).

mm2([S,E,N,D,M,O,R,Y]) :-
     generate2([S,E,N,D,M,O,R,Y],[0,1,2,3,4,5,6,7,8,9]),      % generate + test
     S>0, M >0,                         % test
     test_sum(S,E,N,D,M,O,R,Y).         % test

generate2([X|Xs],Vs):-
     select(X,Vs,Vr),
     generate2(Xs,Vr).
generate2([],_).
    
/*
 | ?-  mm0([S,E,N,D,M,O,R,Y]).

D = 7,
E = 5,
M = 1,
N = 6,
O = 0,
R = 8,
S = 9,
Y = 2 ? 

yes
| ?- statistics(runtime,V).

V = [3832530,3832330] ?        
| ?- mm1([S,E,N,D,M,O,R,Y]).

D = 7,
E = 5,
M = 1,
N = 6,
O = 0,
R = 8,
S = 9,
Y = 2 ? 
| ?- statistics(runtime,V).

V = [3903350,150] ?
-> T = 65 minutes
| ?- mm2([S,E,N,D,M,O,R,Y]).

D = 7,
E = 5,
M = 1,
N = 6,
O = 0,
R = 8,
S = 9,
Y = 2 ?

yes
| ?- statistics(runtime,V).

V = [119250,96380] 
-> T =   22870 (22 s)                     
*/
