1.一个例题关于用匹配模式统计字符串中的不同字母出现的位置并排序
//限制: 不能使用可变map 不能使用sortedlist集合
问题:使用不可变map无法使用map()
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
object Test3 {
def main(args: Array[String]): Unit = {
//统计字母出现的位置
var st :String = "AANNCCCRRUUSSRT"
println(func1(st)(max))
}
//发现一个问题 不可变map不能使用map()原因是map()是调用添加方法的,如果不存在则是添加,存在则是更新
def func1(string: String)(f:String=>String)={
val map = mutable.Map[Char,ListBuffer[Int]]()
var i =0
f(string).foreach {
//foreach方法每次循环获取一个
data=> map.get(data) match {
case Some(value) => map(data) = value :+ i
case None => map += (data -> ListBuffer{i} )
}
i+=1
}
map.toList.sortBy(_._1).reverse
}
def max (string: String)={
string.toUpperCase
}
}
2.unapplySeq方法(提取器)在模式匹配中的使用(对象的匹配)
//字符串的匹配
object Test4 {
def main(args: Array[String]): Unit = {
val st = "小白,小明,小华,小妞"
var result = st match {
case Name(a,_,_,d) => (a,d)
}
println(result)
}
}
object Name{
def unapplySeq(arg: String): Option[Array[String]] ={
if(arg.length==0) None else Some(arg.split(","))
}
}
3.scala模式匹配中的语法及使用
1.用作类型的检查(数据类型的匹配)
2.匹配数据结构(元素的获取和占位符的使用 _ name @_*)
3.提取器(unapply 固定数量 unapplySeq )
4.样例类(编译器进行了自动的配置:构造器的每个参数默认val .....)
网友评论