Skip to content

Instantly share code, notes, and snippets.

View j5ik2o's full-sized avatar

Junichi Kato j5ik2o

View GitHub Profile
@j5ik2o
j5ik2o / gist:1297981
Created October 19, 2011 11:02
Scala - オブジェクト(シングルトン)
class Employee(val name:String)
object EmployeeTable {
def insert(employee:Employee):Unit = { /* DBに保存 */ }
def selectAll:List[Employee] = { /* DBから検索 */ }
}
// EmployeeTableがインスタンスそのもので、クラスは見えないところにある。
EmployeeTable.insert(new Employee("Junichi Kato"))
val employees = EmployeeTable.selectAll
@j5ik2o
j5ik2o / gist:1298006
Created October 19, 2011 11:15
Scala - コンパニオンオブジェクト
package money
import java.util.Currency
import java.util.Locale
class Money(private val amount:BigDecimal, val currency: Currency){
def this(amount:BigDecimal) = this(amount, DEFAULT) // オブジェクトの定数が参照できる
def plus(other:Money) = { /*略*/ }
}
// クラスと同名のオブジェクトを定義できます。
https://gist.github.com/1297952
@j5ik2o
j5ik2o / ReOrderingTest.java
Created November 19, 2011 09:43
リオーダーテスト
package test;
import java.util.concurrent.CountDownLatch;
public class ReOrderingTest {
static int x = 0;
static int y = 0;
static int a = 0;
static int b = 0;
@j5ik2o
j5ik2o / StopThreadTest.java
Created November 19, 2011 09:45
可視性のテスト
package test;
import java.util.concurrent.TimeUnit;
public class StopThreadTest {
private static boolean stopRequested;
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@j5ik2o
j5ik2o / RaceCondTest.scala
Created November 20, 2011 01:00
レースコンディションテスト(Scala)
package actor
import java.util.concurrent.CountDownLatch
import scala.collection.mutable.HashSet
import akka.stm._
class Sequence {
var value = 0
def getValue() = value
def getAndIncrement() = synchronized {
value += 1
@j5ik2o
j5ik2o / Bench.scala
Created November 28, 2011 16:25
パラレルコレクションのデモ
import scala.collection.immutable.NumericRange
object Util {
// nまでの階乗を計算するメソッド
def fac(n: BigInt) =
NumericRange(BigInt(1), n, BigInt(1)).
foldLeft(BigInt(1)){(cur, next) =>
cur * next
}
}
@j5ik2o
j5ik2o / gist:1429210
Created December 4, 2011 04:50 — forked from tyano/gist:1429205
List(1, 2, 3, 1) を Map(1 -> 2, 2 -> 1, 3 -> 1)
List(1,2,3,1).zip(List(1,1,1,1)).foldLeft(Map[Int,Int]()) { (x, y) => x.get(y._1) match { case Some(v) => x + Pair(y._1, (v + y._2)) case None => x + y }}
@j5ik2o
j5ik2o / BenchUtil.scala
Created December 4, 2011 10:02
ベンチマーク用のツール
object BenchUtil {
private def avg(xs:List[BigDecimal]):BigDecimal =
xs.sum / xs.size
private def std(avg:BigDecimal, xs:List[BigDecimal]):BigDecimal =
Math.sqrt((xs.foldLeft(BigDecimal(0))((s,c) => s + (c-avg) * (c+avg)) / xs.size).toDouble)
private def center(xs:List[BigDecimal]) = xs.toSet.toList.sortWith(_ < _) match {
case n :: Nil => n
@j5ik2o
j5ik2o / thread-test.scala
Created December 4, 2011 12:25
Lock & STM
#!/usr/bin/env xsbtscript
!#
/***
scalaVersion := "2.9.1"
resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"
libraryDependencies ++= Seq(
"se.scalablesolutions.akka" % "akka-stm" % "1.2"