Spec2.8Chap8a

第 8 章 パターンマッチング (Pattern Matching)



8.1 パターン (Patterns)

構文:

   Pattern            ::=   Pattern1 { '|' Pattern1 }
   Pattern1           ::=   varid ':' TypePat
                        |   '_' ':' TypePat
                        |   Pattern2
   Pattern2           ::=   varid ['@' Pattern3]
                        |   Pattern3
   Pattern3           ::=   SimplePattern
                        |   SimplePattern {id [nl] SimplePattern}
   SimplePattern      ::=   '_'
                        |   varid
                        |   Literal
                        |   StableId
                        |   StableId '(' [Patterns] ')'
                        |   StableId '(' [Patterns ','] [varid '@'] '_' '*' ')'
                        |   '(' [Patterns] ')'
                        |   XmlPattern
   Patterns           ::=   Pattern {',' Patterns}

A pattern is built from constants, constructors, variables and type tests . Pattern matching tests whether a given value (or sequence of values) has the shape defined by a pattern, and, if it does, binds the variables in the pattern to the corresponding components of the value (or sequence of values). The same variable name may not be bound more than once in a pattern .

パターンは定数、コンストラクタ、変数と型テストから構成されます。 パターンマッチングは、 与えられた値(あるいは値のシーケンス)が パターンによって定義された形をしているかテストし、もしそうなら、 パターン中の変数を対応する値(あるいは値のシーケンス)の構成要素に束縛します。 同じ変数名はパターン中で 1 度より多くは束縛できません。


Example 8.1.1 次はパターンのいくつかの例です:

  1. The pattern ex: IOException matches all instances of class IOException, binding variable ex to the instance .
  2. The pattern Some(x) matches values of the form Some(v), binding x to the argument value v of the Some constructor .
  3. The pattern (x, _) matches pairs of values, binding x to the first component of the pair . The second component is matched with a wildcard pattern .
  4. The pattern x :: y :: xs matches lists of length 2, binding x to the list's first element, y to the list's second element, and xs to the remainder .
  5. The pattern 1 | 2 | 3 matches the integers between 1 and 3 .
  1. パターン ex:IOException は、クラス IOException のすべてのインスタンスとマッチし、変数 ex をインスタンスに束縛します。
  2. パターン Some(x)は、Some(v) の形の値と一致し、x を Some コンストラクタの引数値 v に束縛します。
  3. パターン(x,_)は、値のペアに一致し、x をそのペアの最初の構成要素に束縛します。2 番目の構成要素はワイルドカードパターンとマッチします。
  4. パターン x :: y :: xs は、長さ 2 以上のリストとマッチし、x をリストの最初の要素へ、y をリストの 2 番目の要素へ、xs を残りへ束縛します。
  5. パターン 1 | 2 | 3 は、1 以上 3 以下の整数とマッチします。

Pattern matching is always done in a context which supplies an expected type of the pattern . We distinguish the following kinds of patterns .

パターンマッチングは常に、 パターンの要請型を提供するコンテキスト中で実行されます。 パターンには次の種類の区別があります。



8.1.1 変数パターン (Variable Patterns)

構文:

     SimplePattern    ::=   '_'
                        |   varid

A variable pattern x is a simple identifier which starts with a lower case letter . It matches any value, and binds the variable name to that value . The type of x is the expected type of the pattern as given from outside . A special case is the wild-card pattern _ which is treated as if it was a fresh variable on each occurrence .

変数パターン x は小文字で始まる単純な識別子です。 それは任意の値とマッチし、変数名をその値に束縛します。 x の型は、外側で与えられた、パターンの要請型です。 ワイルドカードパターン _ は特別な場合で、 出現の度に新しい変数であるかのように扱われます。



8.1.2 型付きパターン (Typed Patterns)

構文:

   Pattern1         ::=   varid ':' TypePat
                      |   '_' ':' TypePat

A typed pattern x : T consists of a pattern variable x and a type pattern T . The type of x is the type pattern T , where each type variable and wildcard is replaced by a fresh, unknown type . This pattern matches any value matched by the type pattern T (§8.2); it binds the variable name to that value .

型付きパターン x : T は、パターン変数 x と型パターン T から成ります。 x の型は型パターン T です。ここで各型変数とワイルドカードは、 新規の、未知の型によって置き換えられます。 このパターンは型パターン T によってマッチされる任意の値にマッチします (§8.2); これは変数名をその値に束縛します。



8.1.3 パターンバインダー (Pattern Binders)

構文:

   Pattern2         ::=   varid '@' Pattern3

A pattern binder x@p consists of a pattern variable x and a pattern p . The type of the variable x is the static type T of the pattern p . This pattern matches any value v matched by the pattern p, provided the run-time type of v is also an instance of T , and it binds the variable name to that value .

パターンバインダー(訳注:変数の束縛、あるいは、変数識別子束縛) x@p は、 パターン変数 x とパターン p からなります。 変数 x の型はパターン p の静的な型 T です。 このパターンは、v の実行時型も同じく T のインスタンスなら、 パターン p によってマッチされる任意の値 v にマッチします。 そして変数名をその値に束縛します。



8.1.4 リテラルパターン (Literal Patterns)

構文:

   SimplePattern       ::=   Literal

A literal pattern L matches any value that is equal (in terms of ==) to the literal L . The type of L must conform to the expected type of the pattern .

リテラルパターン L は、リテラル L に(==の意味で)等価な任意の値にマッチします。 L の型はパターンの要請型に適合しなくてはなりません。



8.1.5 安定識別子パターン (Stable Identifier Patterns)

構文:

   SimplePattern       ::=   StableId

A stable identifier pattern is a stable identifier r (§3.1). The type of r must conform to the expected type of the pattern . The pattern matches any value v such that r == v (§12.1) .

安定識別子パターンは安定識別子 r (§3.1)です。 r の型はパターンの要請型に適合しなくてはなりません。 パターンは、r == v である任意の値にマッチします (§12.1)。

To resolve the syntactic overlap with a variable pattern, a stable identifier pattern may not be a simple name starting with a lower-case letter . However, it is possible to enclose a such a variable name in backquotes; then it is treated as a stable identifier pattern .

変数パターンとの構文的な重なりを解決するため、 安定識別子パターンは小文字で始まる単純名ではいけません。 しかし、これはそのような変数名をバッククォートで囲めば可能で、 そうすれば安定識別子パターンとして扱われます。


Example 8.1.2 次の関数定義を考えます。:

   def f(x: Int, y: Int) = x match {
     case y => ...
   }

Here, y is a variable pattern, which matches any value . If we wanted to turn the pattern into a stable identifier pattern, this can be achieved as follows:

ここで y は、任意の値にマッチする変数パターンです。 もしこのパターンを安定識別子パターンに変えたければ、次のようにます。:

   def f(x: Int, y: Int) = x match {
     case `y` => ...
   }

Now, the pattern matches the y parameter of the enclosing function f . That is, the match succeeds only if the x argument and the y argument of f are equal .

これで、パターンは取り囲む関数 f の y パラメータにマッチします。 すなわち、f の x 引数と y 引数が等しい場合に限り、マッチングは成功します。



8.1.6 コンストラクタパターン (Constructor Patterns)

構文:

   SimplePattern       ::=   StableId '(' [Patterns] ')

コンストラクタパターンは c(p1,...,pn) の形です。ここで n >= 0。 これは、安定識別子 c とそれに続く要素パターン p1,...,pn からなります。

The constructor c is a simple or qualified name which denotes a case class (§5.3.2). If the case class is monomorphic , then it must conform to the expected type of the pattern, and the formal parameter types of x's primary constructor (§5.3) are taken as the expected types of the element patterns p1,...,pn .

コンストラクタ c はケースクラス (§5.3.2) を表す単純名あるいは修飾された名前です。 もしケースクラスが単相的なら、 それはパターンの要請型に適合しなくてはならず、また、x の基本コンストラクタ (§5.3) の形式上のパラメータ型は、要素パターン p1,...,pn の要請型とみなされます。 (訳注: x とあるのは c の誤記?)

If the case class is polymorphic, then its type parameters are instantiated so that the instantiation of c conforms to the expected type of the pattern . The instantiated formal parameter types of c's primary constructor are then taken as the expected types of the component patterns p1,...,pn . The pattern matches all objects created from constructor invocations c(v1,...,vn) , where each element pattern pi matches the corresponding value vi .

A special case arises when c's formal parameter types end in a repeated parameter . This is further discussed in (§8.1.9) .

もしケースクラスが多相的なら、 c のインスタンス化がパターンの要請型に適合するように、 型パラメータがインスタンス化されます。 c の基本コンストラクタのインスタンス化された形式上のパラメータ型は、 構成要素パターン p1,...,pn の要請型とみなされます。 パターンは、コンストラクタ呼び出し c(v1,...,vn) から生成されるすべてのオブジェクトにマッチします。 ただしここで、各要素パターン pi は対応する値 vi にマッチします。

c の形式上のパラメータ型が反復パラメータで終わるとき、特別な場合が生じます。 これについては、 さらに(§8.1.9)で論じます。



8.1.7 タプルパターン (Tuple Patterns)

構文:

   SimplePattern   ::=   '(' [Patterns] ')'

A tuple pattern (p1,...,pn) is an alias for the constructor pattern scala.Tuplen (p1,...,pn), where n >= 2. The empty tuple () is the unique value of type scala.Unit .

タプルパターン (p1,...,pn) は、コンストラクタパターン scala.Tuplen(p1,...,pn) のエイリアスです。ここで n >= 2。 空のタプル()は、型 scala.Unit のただ 1 つの値です。



8.1.8 抽出子パターン (Extractor Patterns)

構文:

   SimplePattern        ::=   StableId '(' [Patterns] ')'

An extractor pattern x(p1,...,pn) , where n >= 0 is of the same syntactic form as a constructor pattern . However, instead of a case class, the stable identifier x denotes an object which has a member method named unapply or unapplySeq that matches the pattern .

抽出子パターン x(p1,...,pn) は、ここで n >= 0、 コンストラクタパターンと同じ構文上の形をしています。 しかし、ケースクラスの代わりに、安定識別子 x は、パターンにマッチする unapply あるいは unapplySeq という名前のメンバーメソッドを持つオブジェクトを表します。

An unapply method in an object x matches the pattern x(p1,...,pn) if it takes exactly one argument and one of the following applies:

オブジェクト x 中の unapply メソッドは、もしそれが正確にただ 1 つの引数をとり、 次の 1 つが当てはまるなら、パターン x(p1,...,pn) と マッチ します:

n = 0 and unapply's result type is Boolean. In this case the extractor pattern matches all values v for which x.unapply(v) yields true .

  • n = 0 かつ unapply の結果型は Boolean 。この場合、抽出子パターンは x.unapply(v) が true となる、すべての値 v とマッチします。

n = 1 and unapply's result type is Option[T], for some type T . In this case, the (only) argument pattern p1 is typed in turn with expected type T .The extractor pattern matches then all values v for which x.unapply(v) yields a value of form Some(v1), and p1 matches v1 .

  • n = 1 かつ unapply の結果型が、ある型 T から構成される Option[T] 。 この場合、その(ただ 1 つの)引数パターン p1 は、今度は要請型 T で型付けられます。 このとき抽出子パターンは、x.unapply(v) が Some(v1) の形の値をもたらしそして p1 が v1 にマッチする、すべての値 v とマッチします。

n > 1 and unapply's result type is Option[(T1,...,Tn)], for some types T1,...,Tn . In this case, the argument patterns p1,...,pn are typed in turn with expected types T1,...,Tn . The extractor pattern matches then all values v for which x.unapply(v) yields a value of form Some*1, and each pattern pi matches the corresponding value vi .

  • n > 1 かつ unapply の結果型が、ある型 T1,...,Tn から構成される Option[(T1,...,Tn)] 。 この場合、引数パターン p1,...,pn は、今度は要請型 T1,...,Tn で型付けされます。 このとき抽出子パターンは、x.unapply(v) が Some*2 の形の値をもたらし、そして各パターン pi が 対応する vi にマッチする、すべての値 v とマッチします。

An unapplySeq method in an object x matches the pattern x(p1,...,pn) if it takes exactly one argument and its result type is of the form Option[S], where S is a subtype of Seq[T] for some element type T . This case is further discussed in (§8.1.9) .

オブジェクト x 中の unapplySeq メソッドは、 もしそれが正確にただ 1 つの引数をとり、 その結果型が Option[S] の形なら、パターン x(p1,...,pn)とマッチします。 ここで S はある要素型 T から構成される Seq[T] のサブ型です。 これについては (§8.1.9)でさらに議論されます。


Example 8.1.3 Predef (事前定義済み)オブジェクトは抽出子オブジェクト Pair の定義を 含んでいます:

   object Pair {
     def apply[A, B](x: A, y: B) = Tuple2(x, y)
     def unapply[A, B](x: Tuple2[A, B]): Option[Tuple2[A, B]] = Some(x)
   }

This means that the name Pair can be used in place of Tuple2 for tuple formation as well as for deconstruction of tuples in patterns . Hence, the following is possible:

このことは、名前 Pair が Tuple2 の代わりに、 パターンにおけるタプルの逆構築(deconstruction)と同様に、 タプル形成にも使えることを意味します。 ですから、次が可能です:

   val x = (1, 2)
   val y = x match {
     case Pair(i, s) => Pair(s + i, i * i)
   }



8.1.9 シーケンスパターン (Pattern sequences)

構文:

   SimplePattern ::= StableId '(' [Patterns ','] [varid '@'] '_' '*' ')'

A pattern sequence p1,...,pn appears in two contexts . First, in a constructor pattern c(q1,...,qm , p1,...,pn), where c is a case class which has m + 1 primary constructor parameters, ending in a repeated parameter (§4.6.2) of type S . Second,in an extractor pattern x(p1,...,pn) if the extractor object x has an unapplySeq method with a result type conforming to Seq[S], but does not have an unapply method that matches p1,...,pn . The expected type for the pattern sequence is in each case the type S .

シーケンスパターン p1,...,pn は、2 つのコンテキスト中に現れます。 1 つは、コンストラクタパターン c(q1,...,qm , p1,...,pn) 中です。 ここで c は、m + 1 個の基本コンストラクタパラメータをもつケースクラスで、 パラメータの最後が型 S の反復パラメータ (§4.6.2)のものです。 2 つめは、抽出子パターン x(p1,...,pn) 中です。 ただし、抽出子オブジェクト x は Seq[S] に適合する結果型を返す unapplySeq メソッドを持つが、 しかし p1,...,pn にマッチする unapply メソッドを持たない場合です。 シーケンスパターンの要請型は、それぞれ、型 S です。

The last pattern in a pattern sequence may be a sequence wildcard _*. Each element pattern pi is type-checked with S as expected type, unless it is a sequence wildcard . If a final sequence wildcard is present, the pattern matches all values v that are sequences which start with elements matching patterns p1,...,pn-1 . If no final sequence wildcard is given, the pattern matches all values v that are sequences of length n which consist of elements matching patterns p1,...,pn .

シーケンスパターン中の最後のパターンは、 ワイルドカードシーケンス _* でも構いません。 各要素パターン pi は、それがワイルドカードシーケンスでない限り、 S を要請型として型チェックされます。 もし最後にワイルドカードシーケンスがあれば、そのパターンは、 パターン p1,...,pn-1 にマッチする要素で始まるシーケンスである、 すべての値 v にマッチします。 もし最後にワイルドカードシーケンスが与えられていないなら、そのパターンは、 パターン p1,...,pn にマッチする要素からなる長さ n のシーケンスである、 すべての値 v にマッチします。



8.1.10 中置演算パターン (Infix Operation Patterns)

構文:

   Pattern3   ::= SimplePattern {id [nl] SimplePattern}

An infix operation pattern p op q is a shorthand for the constructor or extractor pattern op(p, q). The precedence and associativity of operators in patterns is the same as in expressions (§6.12) . An infix operation pattern p op (q1,...,qn) is a shorthand for the constructor or extractor pattern op(p, q1,...,qn) .

中置演算パターン p op q は、コンストラクタあるいは抽出子パターン op(p,q) の略記表現です。 パターン中の演算子の優先順位と結合性は、式 (§6.12)中の場合と同じです。 中置演算パターン p op (q1,...,qn) は、コンストラクタあるいは抽出子パターン op(p, q1,...,qn) の略記表現です。



8.1.11 パターン選択 (Pattern Alternatives)

構文:

   Pattern ::= Pattern1 { '|' Pattern1 }

A pattern alternative p1 | ... | pn consists of a number of alternative patterns pi . All alternative patterns are type checked with the expected type of the pattern . They may no bind variables other than wildcards . The alternative pattern matches a value v if at least one its alternatives matches v .

パターン選択 p1 | ... | pn は、多数の選択肢パターン pi からなります。 すべての選択肢パターンは、パターンの要請型で型チェックされます。 それらはワイルドカード以外の変数を束縛しません。 選択パターンは、もし少なくとも 1 つの選択肢が 値 v にマッチするなら、 v にマッチします。



8.1.12 XML patterns (XML Patterns)

XML パターンは §10.2 で扱います。



8.1.13 正規表現パターン (Regular Expression Patterns)

Regular expression patterns have been discontinued in Scala from version 2.0 .

Later version of Scala provide a much simplified version of regular expression patterns that cover most scenarios of non-text sequence processing .

正規表現パターンは、Scala バージョン 2.0 から廃止になりました。

Scala の後のバージョンでは、 非テキストシーケンス処理のほとんどのシナリオをカバーする、 正規表現パターンのより単純化されたバージョンを提供します。

A sequence pattern is a pattern that stands in a position where either (1) a pattern of a type T which is conforming to Seq[A] for some A is expected, or (2) a case class constructor that has an iterated formal parameter A*. A wildcard star pattern _* in the rightmost position stands for arbitrary long sequences . It can be bound to variables using @, as usual, in which case the variable will have the type Seq[A] .

シーケンスパターン とは、次のいずれかの場所にあるパターンです。 (1) 要請される、ある A から構成される Seq[A] に適合する型 T のパターン、 あるいは、(2) 反復する形式上のパラメータ A* を持つケースクラスコンストラクタ。 最も右に位置するワイルドカードの星印パターン _* は、任意長さのシーケンスを 表します。 通常、@を使って変数へ束縛できます。その場合、変数は型 Seq[A] を持ちます。



8.1.14 明白パターン (Irrefutable Patterns)

A pattern p is irrefutable for a type T , if one of the following applies:

  1. p is a variable pattern,
  2. p is a typed pattern x : T´ , and T <: T´ ,
  3. p is a constructor pattern c(p1,...,pn), the type T is an instance of class c, the primary constructor (§5.3) of type T has argument types T1,...,Tn , and each pi is irrefutable for Ti .

パターン p は、もし次の 1 つが当てはまるなら、型 T について 明白(irrefutable) です。:

  1. p は変数パターン。
  2. p は型付きパターン x : T´で、T <: T´。
  3. p はコンストラクタパターン c(p1,...,pn) で、型 T はクラス c のインスタンス、型 T の基本コンストラクタ(§5.3)が引数型 T1,...,Tn をもち、各 pi が Ti について明白(irrefutable)。

タグ:

+ タグ編集
  • タグ:

このサイトはreCAPTCHAによって保護されており、Googleの プライバシーポリシー利用規約 が適用されます。

最終更新:2011年02月23日 18:38
ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。

*1 v1,...,vn

*2 v1,...,vn