16
since 2002.1.6

あなたの猫さんも,カウンタに参加しませんか?

猫タワーをチェック  過去の猫タワーをチェック

2008/7/21
2008/5/4
2003/7/21
2004/3/21
2007/12/31
2008/3/18
2008/3/10
2007/12/30
 
PR: 転職    葬式    マンスリーマンション 神戸    北海道    環境    FX    不動産担保融資    桐ヶ谷斎場    海外旅行    専門学校   

バイトコードを見ると、instanceof使っているんだけど、ということは、複数のcase classが継承関係にある場合、親の方が先のcaseに書かれると、マズイんじゃないだろうか。早速テスト。

abstract class Tree
case class Child extends Tree
case class Child2 extends Child
shanai@shanai-desktop:~/scala$ scalac CaseClass.scala
CaseClass.scala:3 error: implementation restriction: case class Child2 and case class Child cannot be combined in one object
case class Child2 extends Child
     ^
one error found

なるほど、出来ないようになっているわけですか。caseクラス同士は、継承関係にあってはいけないようですな。

ScalaByExampleで、末尾再帰にしてみろとのことだったので、してみた。

  def factorial2(n: int) : int = {
    factorialIter(1, n)
  }

  def factorialIter(sum: int, n: int) : int = {
    if (n == 1) sum else factorialIter(sum * n, n - 1)
  }

で、バイトコードを見てみる。

public int factorialIter(int, int);
  Code:
   Stack=3, Locals=3, Args_size=3
   0:	iload_2
   1:	iconst_1
   2:	if_icmpeq	16
   5:	iload_1
   6:	iload_2
   7:	imul
   8:	iload_2
   9:	iconst_1
   10:	isub
   11:	istore_2
   12:	istore_1
   13:	goto	0
   16:	iload_1
   17:	ireturn

おぉ、ループになってますな。

P.S. Scala的には、こうかな。

  def factorial2(n: int) : int = {
    def factorialIter(sum: int, n: int) : int = {
      if (n == 1) sum else factorialIter(sum * n, n - 1)
    }
    factorialIter(1, n)
  }