Authored by Win Myo Htet
def forall (p: (A) ⇒ Boolean): Boolean
def foreach (f: (A) ⇒ Unit): Unit
Basically forall takes predicates and return Boolean and foreach takes lambda and return nothing.scala> val list=(for (i <- 1 to 25 if i%2 ==0) yield i) toList
list: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24)
scala> list forall(x => x%2==0)
res0: Boolean = true
scala> list foreach println
2
4
6
8
10
12
14
16
18
20
22
24
scala> val print_pretty=(x:Int)=>{println("***"+x+"***")}
print_pretty: Int => Unit = <function1>
scala> list foreach print_pretty
***2***
***4***
***6***
***8***
***10***
***12***
***14***
***16***
***18***
***20***
***22***
***24***
scala>
Now that we are doing some pretty printing, shall we look into some functions that can help with printing?
def addString (b: StringBuilder): StringBuilder
def addString (b: StringBuilder, sep: String): StringBuilder
def addString (b: StringBuilder, start: String, sep: String, end: String): StringBuilder
def mkString : String
def mkString (sep: String): String
def mkString (start: String, sep: String, end: String): String
scala> list
res3: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24)
scala> list.addString(new StringBuilder(""))
res4: StringBuilder = 24681012141618202224
scala> list.addString(new StringBuilder(""),",")
res5: StringBuilder = 2,4,6,8,10,12,14,16,18,20,22,24
scala> list.addString(new StringBuilder(""),"(",",",")")
res6: StringBuilder = (2,4,6,8,10,12,14,16,18,20,22,24)
scala> list.mkString
res7: String = 24681012141618202224
scala> list.mkString(",")
res8: String = 2,4,6,8,10,12,14,16,18,20,22,24
scala> list.mkString("(",",",")")
res9: String = (2,4,6,8,10,12,14,16,18,20,22,24)
Well, that is easy. You know when I first started reading the scala code, I didn't know mkString even and have to google it.andThen ?
Authored by Win Myo Htet
No comments:
Post a Comment