「48時間でSchemeを書こう」の版間の差分

削除された内容 追加された内容
→‎Return Values: 一部訳出
266 行
</syntaxhighlight>
 
=== Return Values戻り値 ===
 
現段階では、パーサは与えられた文字列が認識できるか否かを表示するだけで、特には何もしません。普通、パーサには与えられた入力を扱いやすいデータ構造に変換して欲しいものです。この節では、どのようにデータ型を定義し、パーサがそのデータ型を返すようにするかを学びます。
Right now, the parser doesn't ''do'' much of anything - it just tells us whether a given string can be recognized or not. Generally, we want something more out of our parsers: we want them to convert the input into a data structure that we can traverse easily. In this section, we learn how to define a data type, and how to modify our parser so that it returns this data type.
 
まず、どんなLispの値も保持できるデータ型を定義しなければなりません。
First, we need to define a data type that can hold any Lisp value:
 
<syntaxhighlight lang="haskell">
data LispVal = Atom String
| List [LispVal]
| List [LispVal]
| DottedList [LispVal] LispVal
| Number Integer
| String String
| Bool Bool
</syntaxhighlight>
 
これは''代数的データ型''の一例です。<code>LispVal</code>型の変数が持つことのできる値の集合を定めています。選択肢のそれぞれ(''コンストラクタ''と呼ばれ、<code>|</code>で区切られます)は、コンストラクタのタグとそのコンストラクタが持つことのできるデータの型を含みます。この例では、<code>LispVal</code>は次のどれかです。
This is an example of an ''algebraic data type''<nowiki>: it defines a set of possible values that a variable of type LispVal can hold. Each alternative (called a </nowiki>''constructor'' and separated by <code>|</code>) contains a tag for the constructor along with the type of data that that constructor can hold. In this example, a <code>LispVal</code> can be:
 
# <code>Atom</code> - そのアトムの示す文字列を格納します。
# An <code>Atom</code>, which stores a String naming the atom
# <code>List</code> - 他の<code>LispVal</code>のリストを保持します(Haskellのリストは角括弧で表されます)。''proper''リストとも呼ばれます。
# A <code>List</code>, which stores a list of other LispVals (Haskell lists are denoted by brackets); also called a ''proper'' list
# A <code>DottedList</code>, representing the- Scheme form <code>(a b . c)</code>; also called an を表し、''improper'' list. This stores a list of all elements but the last, and then stores the last element as another fieldリストとも呼ばれます。これは最後以外全ての要素のリストを持ち、最後の要素を別に格納します。
# A <code>Number</code>, containing a- Haskell Integerの整数を保持します。
# A <code>String</code>, containing a- Haskell Stringの文字列を保持します。
# A <code>Bool</code>, containing a- Haskell boolean valueの真偽値を保持します。
 
Constructors and types have different namespaces, so you can have both a constructor named String and a type named String. Both types and constructor tags always begin with capital letters.