作者: Tsutomu Hiroshima
日時: 2002/5/13(15:55)
もう追いつかないので,
課題2のことは忘れることにしよう.

課題3の TeX 版,METAFONT 版,Scheme 版です.

TeX と Scheme は再帰を,
METAFONT は 2進数利用です. 

TeX 版は dvi ファイルも作成します.


%%% TeX版
\newcount\total
\def\showresult#1{
  \begingroup
    \total=0\relax
    \def\insert##1##2{
      \advance\total by ##1\relax
      \if\relax##2
         ##1\message{##1}\let\next\relax
      \else
         ##1 +\message{##1 +}
      \fi
      \next{##2}}
    \let\next\insert
    \insert#1\relax
    \message{= \the\total; }
    = \the\total
  \endgroup
}
\def\subsetadd#1{%
  \begingroup
    \def\dobody##1##2##3\done{%
      \if\relax##3%
	  $\showresult{##1{##2}}$\hfil\break
	\if\relax##1\relax
	  $\showresult{0}$
	\else
	  $\showresult{##1}$\hfil\break
	\fi
      \else
	\dobody{##1{##2}}##3\done
	\dobody{##1}##3\done
      \fi}%
    \dobody{}#1\relax\done
   \endgroup
}
\noindent
\subsetadd{{16}{8}{4}{2}{1}}
\bye


%%% METAFONT 版
v0 := 1; v1 := 2; v2 := 4; v3 := 8; v4 := 16
c := 0;
forever:
  exitif not known v[c];
  c := c + 1;
endfor;
m := mexp(c * mlog 2) - 1;
c := c - 1;
string s;
boolean f;
for b = 0 step 1 until m:
  k := b;
  s := "0";
  f := true;
  r := 0;
  for i = 0 step 1 until c:
    if k mod 2 = 1:
      r := r + v[i];
      if f:
        s := str [v[i]];
        f := false
      else:
        s := s & " + " & str [v[i]]
      fi
    fi;
    k := floor(k / 2);
  endfor;
  s := s & "  =  " & str [r];
  message s;
  message "";
endfor;
end


;;; Scheme 版
(define *set* '(16 8 4 2 1))

(define (subset-addition given-set)
  (define (show-result subset)
    (display (cons '+ subset))
    (display " ==> ")
    (display (apply + subset))
    (newline))	     
  (let loop ((subset '())
	     (first (car given-set))
	     (rest (cdr given-set)))
    (if (null? rest)
	(begin
	  (show-result (append subset (list first)))
	  (show-result subset))
	(begin
	  (let ((f (car rest)) (r (cdr rest)))  
	    (loop (append subset (list first)) f r)
	    (loop subset f r))))))

(subset-addition *set*)
(quit)

-----------------------------
	廣島 勉
	(tsutomu@...)