首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

快学Scala练习题解答—第十三章 集合

2013-02-19 
快学Scala习题解答—第十三章 集合更新scala到版本2.10.0。有可变的可排序的Set,实际上还是TreeSetimport co

快学Scala习题解答—第十三章 集合

更新scala到版本2.10.0。有可变的可排序的Set,实际上还是TreeSet

import collection.mutable.{Map,HashMap,SortedSet}def indexs(str:String):Map[Char,SortedSet[Int]]={  var map = new HashMap[Char, SortedSet[Int]]();  var i = 0;  str.foreach{    c=>      map.get(c) match{        case Some(result) => map(c) = result + i        case None => map += (c-> SortedSet{i})      }      i += 1  }  map}println(indexs("Mississippi")) 

import collection.immutable.HashMapimport collection.mutable.ListBufferdef indexs(str:String):Map[Char,ListBuffer[Int]]={  var map = new HashMap[Char, ListBuffer[Int]]()  var i = 0  str.foreach{    c=>      map.get(c) match{        case Some(result) => result += i        case None => map += (c-> ListBuffer{i})      }      i += 1  }  map}println(indexs("Mississippi"))

def removeZero(nums : List[Int]):List[Int]={  nums.filter(_ != 0)}println(removeZero(List(3,5,0,2,7,0)))

def strMap(strArr : Array[String],map : Map[String,Int]) : Array[Int] = {  strArr.flatMap(map.get(_))}val a = Array("Tom","Fred","Harry")val m = Map("Tom"->3,"Dick"->4,"Harry"->5)println(strMap(a,m).mkString(","))

import collection.mutabletrait MyMkString{  this:mutable.Iterable[String]=>  def myMkString = if( this != Nil) this.reduceLeft(_ + _)}var a = new mutable.HashSet[String] with MyMkStringa += "1"a += "2"a += "3"println(a.myMkString)

得到的结果和lst相同

val lst = List(1,2,3,4,5)println((lst :\ List[Int]())(_ :: _))println((List[Int]() /: lst)((a,b) => b :: a))

val prices = List(5.0,20.0,9.95)val quantities = List(10,2,1)println((prices zip quantities) map { Function.tupled(_ * _) })

def divArr(arr:Array[Double],i:Int)={  arr.grouped(i).toArray}val arr = Array(1.0,2,3,4,5,6)divArr(arr,3).foreach(a => println(a.mkString(",")))

val frequencies = new scala.collection.multable.HashMap[Char,Int] with scala.collection.mutable.SynchronizedMap[Char,Int]

当读到字母c时,他调用

frequencies(c) = frequencies.getOrElse(c,0) + 1

为什么这样做得不到正确答案?如果他用如下方式实现呢:

import scala.collection.JavaConversions.asScalaConcurrentMapval frequencies:scala.collection.mutable.ConcurrentMap[Char,Int] = new java.util.concurrent.ConcurrentHashMap[Char,Int]

并发问题,并发修改集合不安全.修改后的代码和修改前的代码没有什么太大的区别.

val frequencies = new scala.collection.mutable.HashMap[Char,Int]for(c <- str.par) frequencies(c) = frequencies.getOrElse(c,0) + 1

为什么说这个想法很糟糕?要真正地并行化这个计算,他应该怎么做呢?(提示:用aggregate) 并行修改共享变量,结果无法估计。

import scala.collection.immutable.HashMapval str = "abcabcac"val frequencies = str.par.aggregate(HashMap[Char,Int]())(        {                (a,b) =>                 a + (b -> (a.getOrElse(b,0) + 1))    }        ,        {        (map1,map2) =>        (map1.keySet ++ map2.keySet).foldLeft( HashMap[Char,Int]() ) {          (result,k) =>            result + ( k -> ( map1.getOrElse(k,0 ) + map2.getOrElse(k,0) ) )        }     })println(frequencies)
Blog URL: http://www.ivanpig.com/blog/?p=509

热点排行