问题描述
如何使用Scala Actor解决此问题:我有一个程序可以找出给定路径下文件中标识符的频率.假定的编码为UTF-8.我想用scala actor解决同样的问题.
How to solve this using scala Actors:I have a program that finds out the frequencies of identifiers in files under a given path. The encoding assumed is UTF-8. I want to solve the same problem with scala actors.
//program to find frequencies of identifiers
import java.io._
import java.util.concurrent._
import java.util.concurrent.atomic._
object Main {
// visit all files in dir
def processDirectory(dir: File, visit: (File) => Unit) {
for (f <- dir.listFiles)
if (f.isDirectory) processDirectory(f, visit)
else visit(f)
}
//counters for all identifiers
val frequencies = new scala.collection.mutable.HashMap[String, Int]
// Finds all identifiers in a file and increments their counters
def process(f: File) {
val contents = scala.io.Source.fromFile(f, "UTF-8").mkString
val pattern = "[a-zA-Z_][0-9a-zA-Z_]*".r
for (m <- pattern.findAllIn(contents))
frequencies(m) = frequencies.getOrElse(m, 0) + 1
}
def main(args: Array[String]) { //Give path of a directory here
processDirectory(new File(args(0)), process _)
println("Ten most common identifiers:")
val sorted = frequencies.values.toBuffer.sortWith(_ > _)
for (i <- 0 until 10)
for ((k, v) <- frequencies)
if (v == sorted(i)) println(k + " " + v)
}
}
还请解释斯卡拉演员的概念.我对斯卡拉演员感到困惑.
Also please explain the concept of scala actors. I am confused about scala actors.
推荐答案
Actor帮助并发设计.这没有并发的.想要 parallelism 来提高性能的人有时会想做您正在做的事情:进行一些简单的文件系统处理,在其中添加额外的线程,然后看看它是否更快.但是,这是一个磁盘,并且随机访问的成本非常高,因此并行处理,Actor滥用或其他任何处理都无济于事.
Actors help with concurrent design. There's nothing concurrent about this. People who want parallelism, for performance, sometimes want to do exactly what you're doing: take some simple filesystem-munging thing, throw extra threads at it, and see if it's faster. However, this is a disk, and random access is extremely expensive, so you've nothing to gain from parallel processing, Actor-abusing or otherwise.
Scala的演员来自Erlang.因此,请查看以Erlang(pdf)进行的面向并发编程,由Erlang的一位设计师设计,可以帮助您了解他们的想法.他们并不是要在任务上抛出线程以使这些任务更快地运行.
Scala's Actors come from Erlang. So please see if Concurrency Oriented Programming in Erlang (pdf), by one of Erlang's designers, helps you get an idea of what they're about. They're not really about throwing threads at tasks to make those tasks go faster.
一些可帮助Scala演员的资源:
Some resources to help with Scala's Actors:
-
斯卡拉的演员-该书已于本月底发布,但PrePrint PDF现在可用.
Actors in Scala -- it's published at the end of the month, but PrePrint PDFs are available now.
这篇关于如何使用Scala演员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!