22. 一度入れたものは変更不可能
scala> val x = 2
x: Int = 2
scala> x = x + 1
<console>:12: error: reassignment to val
x = x + 1
^
scala> val y = x + 1 // 新 値 返
y: Int = 3
scala> x // 元 変数 変更
res1: Int = 2
22
54. 非変のリストだと
scala> sealed abstract class MyList[+A]
defined class MyList
scala> case object MyNil extends MyList[Nothing]
defined object MyNil
scala> case class MyCons[B](
hd: B,
tl: MyList[B]) extends MyList[B]
defined class MyCons
scala> val list: MyList[Int] = MyNil
//空 表現
<console>:13: error: type mismatch;
found : MyNil.type
required: MyList[Int]
54
55. この三行だけでも色々学べる
sealed abstract class MyList[+A]
case object MyNil extends MyList[Nothing]
case class MyCons[B](
head: B,
tail: MyList[B]
) extends MyList[B]
55
56. headとtail,isEmptyを持たせる
sealed abstract class MyList[+A] {
val head: A
val tail: MyList[A]
def isEmpty: Boolean
}
case object MyNil extends MyList[Nothing] {
val head: Nothing =
throw new NoSuchElementException("head of empty MyList")
val tail: MyList[Nothing] =
throw new NoSuchElementException("tail of empty MyList")
def isEmpty = true
}
case class MyCons(head: A tail: MyList[A]) extends MyList[A] {
def isEmpty = false
56
57. case classの機能
case class MyCons(head: A tail: MyList[A]) extends MyList[A] {
// case class 場合、引数 物 宣言
def isEmpty = false
}
57
68. 例
Man -> Human -> Creature
scala> class Creature
defined class Creature
scala> class Human extends Creature
defined class Human
scala> class Man extends Human
defined class Man
68
69. scala> val list = MyList[Human]() //型 直接指定 事
list: MyList[Human] = MyNil
scala> val CreatureList = new Creature :: list
CreatureList: MyList[Creature]
= MyCons(Creature@5e9b30c4,MyNil)
scala> val HumanList = new Human :: list
HumanList: MyList[Human]
= MyCons(Human@27d684d6,MyNil)
// Human型 下 下限 Human型扱
scala> val ManList = new Man :: list
ManList: MyList[Human] = MyCons(Man@7670cb40MyNil)
69
77. ダメな例(例えば)
def reverse: A = {
var currentList = this
var newList = MyNil // var 使 mutable 方
while(currentList.isEmpty){
var newList = currentList.head :: newList
var currentList = currentList.tail
}
newList
}
77
109. 実装はこんな感じ
def foreach(f: A => Unit): Unit = {
this match {
case MyNil => () // Unit () 表
case MyCons(head, tail) => {
f(head)
t.foreach(f)
}
}
}
109
113. 実装はこんな感じ
def foldLeft[B](z: B)(f: (B, A) => B): B = {
def loop(l: List[A], acc: B)(f: (B, A) => B) =
l match {
case Nil => acc
case Cons(h,t) => loop(t, f(acc,h))(f)
}
loop(this,z)(f)
}
113