i = i if (b) j + j else 0 } val x = maybeTwice2(true, {println("hi"); 1 +41}) // hi // x: Int = 84 lazy val にすると最初に参照された時に、 初めて評価されて結果がキャッシュされる。 Scala の非正格関数は引数を値渡しではなく、名前渡しで受け取る。
{ val buf = new collection.mutable.ListBuffer[A] @annotation.tailrec def go(s: Stream[A]): List[A] = s match { case Cons(h,t) => buf += h() go(t()) case _ => buf.toList } go(this) }
Cons(h, t) if 0 < n => cons(h(), t().take(n - 1)) case _ => empty } 公式の答え. n == 1 のときは empty を詰めるようにすると t() を評価しないで済むた め?? def take(n: Int): Stream[A] = this match { case Cons(h, t) if n > 1 => cons(h(), t().take(n - 1)) case Cons(h, _) if n == 1 => cons(h(), empty) case _ => empty } @annotation.tailrec final def drop(n: Int): Stream[A] = this match { case Cons(_, t) if n > 0 => t().drop(n - 1) case _ => this }
=> B) = this match { case Cons(h, t) => f(h(), t().foldRight(z)(f)) case _ => z } f に渡される二番目の引数が非正格になっているのがポイント。 def exists(p: A => Boolean): Boolean = foldRight(false)((a, b) => p(a) || b) p(a) が true になった場合、b は評価されないで計算が終了する。