for表达式强大而简洁的表现力
-
case class Person(name: String, isMale: Boolean, children: Person*)
-
object For_Expressive {
-
def main(args: Array[String]) {
-
val lauren = Person("Lauren", false)
-
val rocky = Person("Rocky", true)
-
val vivian = Person("Vivian", false, lauren, rocky)
-
val persons = List(lauren, rocky, vivian)
-
-
val result = persons filter (person => !person.isMale) flatMap(person =>
-
(person.children map (child => (person.name, child.name))))
-
println(result)
-
-
val forResult = for (person <- persons; if !person.isMale; child <- person.children) //scala实质上也会将for循环变为map的方式
-
yield (person.name, child.name)
-
println(forResult)
-
}
-
}
Scala中For表达式的生成器、定义和过滤器
-
object ForInAction {
-
def main(args: Array[String]) {
-
val lauren = Person("Lauren", false)
-
val rocky = Person("Rocky", true)
-
val vivian = Person("Vivian", false, lauren, rocky)
-
val persons = List(lauren, rocky, vivian)
-
-
val forResult = for {person <- persons; name = person.name; if !person.isMale; child <- person.children} //生成器、定义、过滤器
-
yield (person.name, child.name)
-
println(forResult)
-
-
val content =for(x <- List(1,2,3); y <- List("Hadoop","Spark","Flink")) yield(x,y) //两个生成器
-
println(content)
-
}
-
}
使用For表达式做查询
-
case class Book(title : String , authors : List[String])
-
object For_Query {
-
def main(args: Array[String]) {
-
val books: List[Book] = List(
-
Book("Structure and Interpretation ", List("Abelson , Harold", "Sussman")),
-
Book("Principles of Compiler Design",
-
List("Aho, Alfred", "Ullman, Jeffrey")),
-
Book("Programming in Modula-2", List("Wirth, Niklaus")),
-
Book("Introduction to Functional Programming", List("Bird, Richard")),
-
Book("The Java Language Specification",
-
List("Gosling, James", "Joy, Bill", "Steele, Guy", "Bracha, Gilad")))
-
-
// val result = for(b <- books ; a <- b.authors if a startsWith "Gosling") yield b.title
-
val result = for(b <- books if (b.title indexOf "Programming") >= 0 ) yield b.title
-
println(result)
-
}
-
}
使用For表达式实现map、flatMap、filter
-
object For_Advanced {
-
def main(args: Array[String]) {}
-
def map[A, B](list: List[A], f: A => B): List[B] =
-
for(element <- list) yield f(element)
-
def flatMap[A, B](list: List[A], f: A => List[B]): List[B] =
-
for(x <- list; y <- f(x)) yield y
-
def filter[A](list: List[A], f: A => Boolean): List[A] =
-
for(elem <- list if f(elem)) yield elem
-
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/28912557/viewspace-2088057/
,如需转载,请注明出处,否则将追究法律责任。