Skip to content

Instantly share code, notes, and snippets.

@rirakkumya
rirakkumya / strProblem.scala
Created March 18, 2012 15:00
最長重複文字列問題
def maxDupStr(str:String) = {
def tails:String => List[String] = {
case "" => Nil
case x => x :: tails(x.tail)
}
val sorted = tails(str) sorted
val pair = sorted zip sorted.tail
val maxPair = {
pair map { case (s1,s2) => (s1 zip s2 filter {c => c._1 == c._2} size, s1)} max
}
@rirakkumya
rirakkumya / build.sbt
Created March 22, 2012 11:29
漢数字変換 by scala parser combinator
libraryDependencies += "org.scala-tools.testing" %% "scalacheck" % "1.9"
scala> object scala {type Int = String}
scala> val dd:scala.Int = 33
<console>:11: error: type mismatch;
found : scala.Int(33)
required: scala.Int
val dd:scala.Int = 33
^
@rirakkumya
rirakkumya / hexToStr.scala
Created April 13, 2012 01:35
16進文字列をAscii文字列に変換
import scala.annotation.tailrec
def hexToStr(s:String):String = {
@tailrec def r(target:String,result:String):String = {
target splitAt 2 match {
case (xx,xs) if !xx.isEmpty => r(xs,result + Integer.parseInt(xx,16).toChar)
case _ => result
}
}
r(s,"")
}
def index(id:String) = Action {
getFirstData(id)
}
private def getFirstData(id:String) = {
Cache.get(id) match {
case Some(id2) => getSecondData(id2)
case None => NotFound
}
}
private def getSecondData(id2:String) = {
scala> for{(x,y) <- Right((3,4)).right} yield (x,y)
<console>:10: error: constructor cannot be instantiated to expected type;
found : (T1, T2)
required: Either[Nothing,(Int, Int)]
for{(x,y) <- Right((3,4)).right} yield (x,y)
scala> Right((3,4)).right map {case (x,y) => (x,y)}
res118: Product with Either[Nothing,(Int, Int)] with Serializable = Right((3,4))
@rirakkumya
rirakkumya / build.sbt
Created April 18, 2012 02:12
iTextとscala-ioでpdfを出力しちゃうコード
libraryDependencies += "com.github.scala-incubator.io" %% "scala-io-core" % "0.3.0"
libraryDependencies += "com.github.scala-incubator.io" %% "scala-io-file" % "0.3.0"
def foo[A,B](in:Option[A])(valid:PartialFunction[Option[A],Either[B,A]])(invalid:PartialFunction[Option[A],Either[B,A]])(other: =>Either[B,A]) = {
if(!valid.isDefinedAt(in) && !invalid.isDefinedAt(in)) {
other
}else{
(valid orElse invalid)(in)
}
}
def getFirstData(id:String) = {
foo(Cache.get(id)){
@rirakkumya
rirakkumya / build.sbt
Created April 27, 2012 05:43
iTextとJFreeChartとscala-ioでpdfにグラフを出力しちゃうコード(日本語対応)
libraryDependencies += "com.github.scala-incubator.io" %% "scala-io-core" % "0.3.0"
libraryDependencies += "com.github.scala-incubator.io" %% "scala-io-file" % "0.3.0"
@rirakkumya
rirakkumya / sheep.scala
Created May 2, 2012 08:48
羊さんコード
case class Sheep(name:String,father:Option[Sheep],mother:Option[Sheep])
object SampleBase {
def father(sheep:Sheep):Option[Sheep] = sheep match {
case Sheep(_, s, _) => s
case _ => None
}
def mother(sheep:Sheep):Option[Sheep] = sheep match {
case Sheep(_, _, s) => s
case _ => None