このディレクトリの索引
http://hibari.2ch.net/test/read.cgi/tech/1305867431/412
#  [1] 授業単元:C  
#  [2] 問題文(含コード&リンク):1~nまでの整数の和を求めるプログラムを次の条件で作成 
#  (1)findall述語、for述語を使用 
#  (2)再帰述語を使用 
#  (3)is 評価をしないもの    
#  

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

'1~nまでの整数の和を求める'(1,1).
'1~nまでの整数の和を求める'(M,_和) :-
        M > 1,
        M1 is M - 1,
        '1~nまでの整数の和を求める'(M1,_和1),
        _和 is M + _和1.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

'1~nまでの整数の和を求める'(_n,_和) :-
        '1~nまでの整数の和を求める'(1,_n,0,_和).

'1~nまでの整数の和を求める'(_n,_n,S1,S) :-
        S is _n + S,!.
'1~nまでの整数の和を求める'(M,_n,S1,S) :-
        M2 is M + 1,
        S2 is M + S1,
        '1~nまでの整数の和を求める'(M2,_n,S2,S).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

'1~nまでの整数の和を is/2 を使わずに再帰的に求める'(_n,_和) :-
        length(L1,_n),
        '1~nまでの整数の和をリストで求める'(L1,L2),
        length(L2,_和).

'1~nまでの整数の和をリストで求める'([],[]).
'1~nまでの整数の和をリストで求める'([_|L1],L2) :-
        '1~nまでの整数の和をリストで求める'(L1,L3),
        append([_|L1],L3,L2).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

'1~nまでの整数の和を findall/3 と for/3 と sum/2 を使って求める'(_n,_和) :-
        findall(M,for(1,M,_n),L),
        sum(L,_和).

sum([],0).
sum([N|R],S) :- sum(R,S1),S is N + S1.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

'1~nまでの整数の和を is/2 を使わずに求める'(_n,_和) :-
        findall(L,(
                    for(1,M,_n),
                    length(L,M)),
                LL),
        flat(LL,L2),
        length(L2,_和).

flat([],[]).
flat([L1|R1],L) :-
        list(L1),
        flat(L1,L11),
        append(L11,L2,L),
        flat(R1,L2).
flat([A|R1],[A|R2]) :-
        flat(R1,R2).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

'1~nまでの整数の和を is/2 を使わずに求める'(_n,_和) :-
        length(L,_n),
        '1~nまでの整数の和を is を使わずに求める'([],L,[],SL),
        length(SL,_和).

'1~nまでの整数の和を is/2 を使わずに求める'(L,L,SL1,SL) :-
        append(L,SL1,SL),!.
'1~nまでの整数の和を is/2 を使わずに求める'(L1,L,SL1,SL) :-
        append(L1,SL1,SL2),
        '1~nまでの整数の和を is/2 を使わずに求める'([_|L1],L,SL2,SL).