Scalaに投稿されたコード一覧

Scala 正規表現

val regex = "([0-9]+.[0-9]+.[0-9]+.[0-9]+).*([0-3][0-9].[A-Z][a-z][a-z].20[0-1][0-9]:[0-2][0-9]:[0-5][0-9]:[0-5][0-9]).*".r;

scala.io.Source.fromFile("./access_log").getLines().foreach( x => { x match { case regex(ip,date) => {println(ip +" at " + date) } case _ => println("no match") }}

Scala 文字列に適当な変換を行なってOptionへ格納する。

import java.text.{SimpleDateFormat => SDF}

val sdf = new SDF("yyyy-MM-dd'T'HH:mm:ssZ")

def convertInt(x: String) = x.toInt
def convertDate(x: String) = sdf.parse(x)

def toOption[T](x: String, converter: String => T = (str: String) => str) = {
  try {
    x match { case "" => None; case other => Some(converter(other)) }
  } catch {
    case e: Exception => None
  }
}

// 使い方
scala> toOption("aaa")
res0: Option[String] = Some(aaa)

scala> toOption("123", convertInt _)
res1: Option[Int] = Some(123)

scala> toOption("2011-07-30 12:34:56", convertDate _)
res2: Option[java.util.Date] = None

scala> toOption("2011-07-30T12:34:56+0900", convertDate _)
res3: Option[java.util.Date] = Some(Sat Jul 30 12:34:56 JST 2011)

Scala 謎言語ウキャス

/**
  * 謎言語ウキャス
  *  こんにちわ →  ᓦᐓᔦᐓᓾᐓᓴᐓᔢᐓ
  *  吾輩は猫である。名前はまだ無い。 → ᗟᐡᓢᐹᔂᐓᑙᐮᓺᐓᓕᐓᔞᐓ。ᖮᐡ᙭ᐠᔂᐓᔑᐓᓳᐓᓎᐭᓗᐓ。
  *  謎言語ウキャスは、@yuroyoroがScalaでテキトーに10分くらいで実装しました。
  *    →  ᗅᐷᒷᐷᕕᐷᔹᐓᕀᐓᕶᐓᕌᐓᔂᐓ、@yuroyoroᓟᐓScalaᓺᐓᕙᐓᕀᐓᕛᐓᖏᐓᓾᐓ10ᘦᐠᓢᐓᔜᐓᓗᐓᓺᐓᗃᐤᗻᐶᓪᐓᔑᐓᓪᐓᓲᐓ。
  *
  */
object UCAS extends App{
  import java.text.Normalizer
  import java.lang.Character.UnicodeBlock

  def toUcasChar(c:Char) = {
    def g(n:Int):Char = (n + 5120).toChar
    def worker(xs:Seq[Char], n:Int):Seq[Char] = if( n < 639 ) xs :+ g(n) else worker( xs :+ g(n % 639), n / 639)

    if( isHKC(c) ) worker(Seq.empty[Char], c.toInt) else Seq(c)
  }

  def fromUcasChar(a:Char, b:Char) = {
    (( (b.toInt - 5120) * 639 ) + a.toInt - 5120 ).toChar
  }

  def isHKC(c:Char) = UnicodeBlock.of(c) match {
    case UnicodeBlock.HIRAGANA | UnicodeBlock.KATAKANA  | UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS => true
    case _ => false
  }

  def isUcas(c:Char) = UnicodeBlock.of(c) == UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS

  def encode(s:String) = {
    Normalizer.normalize(s, Normalizer.Form.NFKC).map{ toUcasChar }.flatten.mkString
  }

  def decode(s:String) = {
    def worker( xs:List[Char], res:List[Char]):List[Char] = xs match {
      case a::b::t if isUcas(a) && isUcas(b) => worker( t, res :+ fromUcasChar(a, b))
      case h::t => worker(t, res :+ h)
      case _ => res
    }

    worker( s.toList, List.empty[Char] ).mkString
  }

  def rand(n:Int = 140) = {
    scala.io.Codec.toUTF8 ((1 to n).map{_ => (util.Random.nextInt(639) + 5120).toChar})
  }

  def readFromStdIn = scala.io.Source.fromInputStream(java.lang.System.in).mkString

  args.headOption.foreach{ cmd => cmd match {
    case "rand" =>
      val n = args.tail.headOption.map{ _.toInt}.getOrElse(140)
      rand(n).foreach{b => java.lang.System.out.write(b)}
    case "decode" =>
      if(args.tail.isEmpty) println(decode(readFromStdIn))
      else args.tail.foreach{ s => println(decode(s)) }
    case "encode" =>
      if(args.tail.isEmpty) println(encode(readFromStdIn))
      else args.tail.foreach{ s => println(encode(s)) }
    case _ =>
      println("""usage: scala UCAS (rand|decode|encode) <strings...>""")
    }
  }

}

Scala X-c3mY4ku)0?HQNOY9QdyNmq$SW|Jh[J?u#lFM\o]p6Pj;l|c_G|0.E;:LfJ5I6.,@mHVfV?wbF*@YWmU-,2#ucmlzp>Y9Q1ICWfMs?M81vwG1n[Tkxa\WM<BS/R$p!n^<pD%R&5jWx;

Stream.continually(util.Random.nextPrintableChar) take(140) mkString

Scala Stringのmap()

scala> "1234567789".map( x => x )
res0: String = 1234567789

scala> "1234567789".map( x => Option(x) )
res1: scala.collection.immutable.IndexedSeq[Option[Char]] = Vector(Some(1), Some(2), Some(3), Some(4), Some(5), Some(6), Some(7), Some(7), Some(8), Some(9))

Scala テスト

"1234567890".reverse.sliding(3,3).map( x => x.reverse).toList.reverse.mkString(",");

Scala 名前つき引数による呼び出し

scala>  def date(year:Int, month:Int, day:Int) = "%s/%02d/%02d" format(year, month, day)
date: (year: Int,month: Int,day: Int)String

scala> date(2011, 07, 18)
res22: String = 2011/07/18

scala> date(day=19, year=2011, month=07)
res23: String = 2011/07/19

Scala 引数の省略は後ろの引数から省略されていると解釈される

scala> def date(month:Int=10, day:Int) = "%s/%s" format (month, day)
date: (month: Int,day: Int)String

scala> date(30)
<console>:7: error: not enough arguments for method date: (month: Int,day: Int)String.
Unspecified value parameter day.
       date(30)
           ^

scala> date(10,30)
res20: String = 10/30

Scala デフォルト引数に指定する式には他の引数の値を利用することができない

scala> def log(msg:String, length:Int = msg.length) = "[%s] %s" format(length, msg)
<console>:5: error: not found: value msg
       def log(msg:String, length:Int = msg.length) = "[%s] %s" format(length, msg)
                                        ^

scala> def log(msg:String)(length:Int = msg.length) = "[%s] %s" format(length, msg)
log: (msg: String)(length: Int)String

scala> log("aaa bbb cccc")()
res18: String = [12] aaa bbb cccc

Scala 引数を指定している関数は()を省略することができない

scala> def now(time:java.util.Date = new java.util.Date) = time.toString
now: (time: java.util.Date)java.lang.String

scala> now
<console>:7: error: missing arguments for method now in object $iw;
follow this method with `_' if you want to treat it as a partially applied function
       now
       ^

scala> now()
res17: java.lang.String = Wed Jul 20 05:50:25 JST 2011
Total Pages: 1 / 212

よく投稿されているコード

タグ

最近投稿されたコード