Más contenido relacionado Similar a Scalaを触ってみた (20) Scalaを触ってみた14. PATTERN MATCH
使ったもの
• 柔軟なswitch文
instanceList foreach {
_ match {
case ClassA => println(“This is ClassA”)
case ClassB if _.hasChild()
=> println(“This is ClassB having ching”)
case _ => println(“other class”)
}
}
(foreach要素を受ける)
(クラスでマッチング)
(さらに if で条件付き)
(デフォルト)
16. SYNTAX SUGAR
使ったもの
• 文字列 -> XML
val nodes:NodeSeq = XML loadString str
• XMLタグ取得
xml “tagName”
• XML要素取得
xml “@attrName”
nodes foreach { _ match { case ~ } }
18. OBJECT
使ったもの
• シングルトンなクラス (Scalaにstaticはない)
object ProjectModelCreator {
def apply(rootUrl: String) = {
var projects = List.empty[Project]
for (url <- SvnCommander.recursiveList(rootUrl)) {
projects = new Project(url) :: projects
}
projects
}
}
!
ProjectModelCreator(“http://localhost/svn”) <= ( ~ ) はapplyメソッドの呼出し
22. IMPLICIT KEYWORD
使いたかったもの
val str:String = 10 <= エラー
implicit def intToString(num: Int): String = { num.toString }
val str:String = 10 <= 成功
• 型チェックでエラーとなる式について、式の正当性を満たす型変換
を実施するimplicitメソッドが、スコープ内で唯一つのとき成功する
23. PARALLEL COLLECTION
使いたかったもの
scala> def exec(num: Int) = {
| Thread.sleep(1000)
| println("num = " + num)
| }
exec: (num: Int)Unit
!
scala> def measure = {
| val start = System.currentTimeMillis()
| for(i <- List(1,2,3,4,5)){ exec(i) }
| println((System.currentTimeMillis() - start) + "[ms]")
| }
measure: Unit
scala> measure
num = 1
num = 2
num = 3
num = 4
num = 5
5008[ms]
• 普通に実行
24. PARALLEL COLLECTION
使いたかったもの
scala> def exec(num: Int) = {
| Thread.sleep(1000)
| println("num = " + num)
| }
exec: (num: Int)Unit
!
scala> def parallelMeasure = {
| val start = System.currentTimeMillis()
| for(i <- List(1,2,3,4,5).par){ exec(i) }
| println((System.currentTimeMillis() - start) + "[ms]")
| }
measure: Unit
scala> parallelMeasure
num = 1
num = 4
num = 2
num = 3
num = 5
2022[ms]
• 並列実行
scala> scala.collection.parallel.availableProcessors
res2: Int = 4
25. PARALLEL COLLECTION
使いたかったもの
scala> def exec2(num: Int) = {
| println("num = " + num + “ start”)
| Thread.sleep(num * 1000)
| println("num = " + num + “ end”)
| }
exec: (num: Int)Unit
!
scala> def measure2 = {
| val start = System.currentTimeMillis()
| for(i <- List(1,2,3,4,5).par){ exec2(i) }
| println((System.currentTimeMillis() - start) + "[ms]")
| }
measure: Unit
scala> parallelMeasure3
num = 1 start
num = 3 start
num = 2 start
num = 4 start
num = 1 end
num = 2 end
num = 5 start
num = 3 end
num = 4 end
num = 5 end
7005[ms]
• ?
常にコアの数だけ並行処理できるわけではない
28. CURRYING
使いたかったもの
• カリー化(curried)
scala> def sum(a:Int, b:Int, c:Int):Int = { a + b + c }
sum: (a: Int, b: Int, c: Int)Int
!
scala> val g = sum _
g: (Int, Int, Int) => Int = <function3>
!
scala> val c = g.curried
c: Int => (Int => (Int => Int)) = <function1>
!
scala> c(1)(2)(3)
res0: Int = 6
関数オブジェクト取得
関数定義
カリー化
カリー化関数の使用
30. CONCLUSION
まとめ
• Better Java
• とりあえずCollectionとclass周りを固めていきたい
• ScalaではPattern Matchが肝な気がした
• IDEはIntelliJ IDEA使いました
• Eclipseショートカットに設定すればそこまでアレルギー無い
• 英語UIが慣れないけど…