Scala School (7)

Types in Scala

次は Type & polymorphism basics なんですがハードルががつっと上がりました。type inference (型推論) とか existential quantification とかorz
とは言え、例示されてる以下の強力さは分かります。

Parametric polymorphism

scala> def drop1[A](l: List[A]) = l.tail
drop1: [A](l: List[A])List[A]

scala> drop1(List(1, 2, 3))
res0: List[Int] = List(2, 3)

List の tail というメソドは cdr なんですね。つうか [A] な表現て今まで出てきてたのかなぁ。type variables か。

Scala has rank-1 polymorphism

ここで例示されてるソレ達の理解が若干微妙。too generic な例、なのか。例示されているソレを REPL に吸わせてみます。まず toList メソドの定義。

scala> def toList[A](a: A) = List(a)
toList: [A](a: A)List[A]

で、最初の foo を定義します。

scala> def foo[A, B](f: A => List[A], b: B) = f(b)
<console>:7: error: type mismatch;
 found   : b.type (with underlying type B)
 required: A
       def foo[A, B](f: A => List[A], b: B) = f(b)
                                                ^

おうふ。定義の時点で駄目って言われるんすね。f は引数一つで A 型、戻りは A 型のリスト。b は B 型、なので現時点で判断不可能、ってことなのかどうなのか。
あるいはもう一つ。

scala> def foo[A](f: A => List[A], i: Int) = f(i)
<console>:7: error: type mismatch;
 found   : i.type (with underlying type Int)
 required: A
       def foo[A](f: A => List[A], i: Int) = f(i)
                                               ^

これも Int と A が同じかどうかが分からないのか。type mismatch という記述がありますね。

Type inference

出た。型推論。In scala all type inference is local. の local の意味がアレ。例示されているソレを確認してみます。

scala> def id[T](x: T) = x
id: [T](x: T)T

最初は id に Int な 322 を食わせていますね。

scala> val x = id(322)
x: Int = 322

あるいは String

scala> val x = id("hey")
x: java.lang.String = hey

あるいは配列

scala> val x = id(Array(1, 2, 3, 4))
x: Array[Int] = Array(1, 2, 3, 4)

む、戻り値の型は基本的に Scala が推論してくれるのか。すごいな。つうかここで一旦止めます。難しすぎる。