「48時間でSchemeを書こう/評価: 第二部」の版間の差分

削除された内容 追加された内容
最初のセクションを訳出
78 行
</syntaxhighlight>
 
== Conditionals条件分岐: Pattern Matching パターンマッチ2 ==
 
では次に、我々の評価器にif節を加えましょう。標準Schemeと同じように、私たちの評価器は<code>#f</code>を偽とし、それ以外の値全てを真とします。
Now, we'll proceed to adding an if-clause to our evaluator. As with standard Scheme, our evaluator considers #f to be false and any other value to be true:
 
<syntaxhighlight lang="haskell">
eval (List [Atom "if", pred, conseq, alt]) =
do result &lt;<- eval pred
case result of
Bool False -&gt;> eval alt
otherwise -&gt;> eval conseq
</syntaxhighlight>
 
これは入れ子のパターンマッチの例です。ここでは、4つの要素を持つリストに対してマッチを行っています。4要素の内、最初はアトム"if"でなければなりませんが、他はどんなSchemeの式でもよいです。最初の引数を取って評価し、それが真であればその次を、偽であればその次の次の式を評価します。
This is another example of nested pattern-matching. Here, we're looking for a 4-element list. The first element must be the atom "if". The others can be any Scheme forms. We take the first element, evaluate, and if it's false, evaluate the alternative. Otherwise, we evaluate the consequent.
 
コンパイル・実行してください。条件分岐で遊ぶことができます。
Compile and run this, and you'll be able to play around with conditionals:
 
<syntaxhighlight lang="text">
debian:/home/jdtang/haskell_tutorial/code#% ghc -package parsec -o simple_parser [../code/listing6.2.hs listing6.2.hs]
debian:/home/jdtang/haskell_tutorial/code#% ./simple_parser "(if (&gt;> 2 3) \"no\" \"yes\")"
"yes"
debian:/home/jdtang/haskell_tutorial/code#% ./simple_parser "(if (= 3 3) (+ 2 3 (- 5 1)) \"unequal\")"
9
</syntaxhighlight>
 
== List Primitives: car, cdr, and cons ==