scala> val abcde = List('a', 'b', 'c', 'd', 'e') abcde: List[Char] = List(a, b, c, d, e) scala> abcde.zipWithIndex res15: List[(Char, Int)] = List((a,0), (b,1), (c,2), (d,3), (e,4))
An implicit parameter is a parameter to method or constructor that is marked as implicit. This means that if a parameter value is not supplied then the compiler will search for an "implicit" value defined within scope (according to resolution rules.) Implicit parameter resolution rules will be discussed soon.
One important restriction is that there can only be a single implicit keyword per method. It must be at the start of a parameter list (which also makes all values of that parameter list be implicit). I further understand that only the last parameter list may be implicit.
// (x: Option[A]) => x map f 可以寫成 _ map f def lift[A, B](f: A => B): Option[A] => Option[B] = (x: Option[A]) => x map f val absO: Option[Double] => Option[Double] = lift(math.abs) // 注意! 用 map/flatMap 實現不容易閱讀。把 Option 當作 List,用 for-comprehension 實現。 def map2[A, B, C](a: Option[A], b: Option[B])(f: (A, B) => C): Option[C] = for { aa <- a bb <- b } yield f(aa, bb)
def traverse[A, B](a: List[A])(f: A => Option[B]): Option[List[B]] = a match { case Nil => Some(Nil) case h::t => map2(f(h), traverse(t)(f))(_ :: _) }
// cond - call by value // onTrue, onFalse - call by name def if2[A](cond: Boolean, onTrue: => A, onFalse: => A): A = if (cond) onTrue else onFalse // onTrue 和 onFalse 在傳入 if2 時不會被求值,此時才會根據 cond 決定誰被求值。 def if2[A](cond: Boolean, onTrue: () => A, onFalse: () => A): A = if (cond) onTrue() else onFalse() // 上面代碼是此版本的語法糖。onTrue 和 onFalse 分別是 lamda function。
def maybeTwice(b: Boolean, i: => Int) = if (b) i + i else 0 // i 被引用兩次,由於 i 是 call-by-name,代表 i 會被求值兩次。 val x = maybeTwice(true, { println("hi"); 1 + 41 }) // 印出兩次 "hi",x = 84。 def maybeTwice(b: Boolean, i: => Int) = { lazy val j = i // j 第一次被引用,會對 i 求值,並將該值 cache 起來; 後續引用 j 不再對 i 求值。 if (b) j + j else 0 // i 被引用兩次,由於 i 是 call-by-name,代表 i 會被求值兩次。 val x = maybeTwice(true, { println("hi"); 1 + 41 }) // 印出一次 "hi",x = 84。
scala> (1 to 5).toList res10: List[Int] = List(1, 2, 3, 4, 5) // list 中所有元素立刻被求值。 scala> (1 to 5).toStream res11: scala.collection.immutable.Stream[Int] = Stream(1, ?) // ? 代表剩下部分未被求值。
$ sbt set scalaVersion := "2.12.1" set libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.2.9" set initialCommands += "import scalaz._, Scalaz._" session save console
# 下載 scalaz-core_2.12-7.2.9.jar $ scala -cp scalaz-core_2.12-7.2.9.jar