1.使用foldLeft方法计算一个列表所有字符串的长度
val list = List("a", "bb", "ccc", "dddd")
list.foldLeft(0)((sum, value)=> sum + value.size)
2.编写一个ccensor trait,包含一个可将pucky和beans替换为shoot何darn的方法,使用映射存储脏话和它们的替代品
trait Censor {
val map = Map(
"Pucky" -> "Shoot",
"Beans" -> "Darn"
)
def transform(words:String) = {
map.foldLeft(words)(
(words, mapReplace) =>
words.replaceAll(
("(?i)\\b" + mapReplace._1 + "\\b"),
mapReplace._2
)
)
}
}
class Say extends Censor
val hello = new Say()
println(hello.transform("hello Pucky and Beans"))
3.从一个文件中加载脏话或它们的代替品
import scala.io.Source
if (args.length > 0) {
val lines = Source.fromFile(args(0)).getLines.toList
for (line <- lines) {
var words = line split " "
for(word <- words) {
word match {
case "Pucky" => println(word)
case "Shoot" => println(word)
case "Beans" => println(word)
case "Darn" => println(word)
case _ =>
}
}
}
} else {
Console.err.println("Please enter filename")
}