元ネタ → http://d.hatena.ne.jp/bleis-tift/20090930/1254309201
何か流行ってるみたいなので、やってみる。
perlは簡単すぎて面白くないので、
use List::Util qw/sum/;
print sum 1 .. (shift or 10);
XSLTで、しかも久し振りに XSLT 1.0でHTML出力
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
<xsl:output method="html" />
<xsl:template match="/root">
<html>
<body>
<xsl:apply-templates select="./*" />
</body>
</html>
</xsl:template>
<xsl:template match="num">
<p>1 から <xsl:value-of select="." /> の総和:
<xsl:call-template name="sum">
<xsl:with-param name="n" select="number(.)" />
<xsl:with-param name="m" select="0" />
</xsl:call-template>
</p>
</xsl:template>
<xsl:template name="sum">
<xsl:param name="n" />
<xsl:param name="m" />
<xsl:choose>
<xsl:when test="$n <= 1">
<xsl:value-of select="$n + $m" />
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="sum">
<xsl:with-param name="n" select="$n - 1" />
<xsl:with-param name="m" select="$m + $n" />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
適応するXMLはこんな感じ
<root>
<num>10</num>
<num>100</num>
<num>1000</num>
</root>
サンプル も用意してみたのでどうぞ
...
と、いうか、まぁXSLTはループを使って変数を更新していくなんてことができないので、再帰的に処理をせざるを得ないのですけどね。





コメントする