관리 메뉴

nkdk의 세상

Scala에 주요 기능들 혹은 샘플 소스 ^^ 본문

My Programing/Scala&Lift

Scala에 주요 기능들 혹은 샘플 소스 ^^

nkdk 2010. 6. 3. 01:38
이번에는 주요 기능들이라기 하기 모한 샘플 소스들 입니다. 보고 이해 하세요 ^^

Abstract Types

object abstractTypes extends Application {
  abstract class Buffer {
type T; val element: T
}
abstract class SeqBuffer {
type T; val element: Seq[T]; def length = element.length
}
def newIntBuffer(el: Int) = new Buffer {
type T = Int; val element = el
}
def newIntBuffer(el: Int*) = new SeqBuffer {
type T = Int; val element = el
}
println(newIntBuffer(1).element)
println(newIntBuffer(1, 2, 3).length)
}
Result:
1
3

BigInt

/** Bigint's can be used seamlessly */
object bigint extends Application {
def factorial(n: BigInt): BigInt =
if (n == 0) 1 else n * factorial(n-1)

val f50 = factorial(50); val f49 = factorial(49)
println("50! = " + f50)
println("49! = " + f49)
println("50!/49! = " + (f50 / f49))
}

Complex Operations

object complexOps extends Application {
  class Complex(val re: Double, val im: Double) {
    def + (that: Complex) =
      new Complex(re + that.re, im + that.im)
    def - (that: Complex) =
      new Complex(re - that.re, im - that.im)
    def * (that: Complex) =
      new Complex(re * that.re - im * that.im,
                  re * that.im + im * that.re)
    def / (that: Complex) = {
      val denom = that.re * that.re + that.im * that.im
      new Complex((re * that.re + im * that.im) / denom,
                  (im * that.re - re * that.im) / denom)
    }
    override def toString =
      re + (if (im < 0) "-" + (-im) else "+" + im) + "*i"
  }
  val x = new Complex(2, 1); val y = new Complex(1, 3)
  println(x + y)
}

For and Yield

/** Turn command line arguments to uppercase */
object Main {
def main(args: Array[String]) {
val res = for (a <- args) yield a.toUpperCase
println("Arguments: " + res.toString)
}
}

Extend Builtins

/* Adding ! as a method on int's */
object extendBuiltins extends Application {
def fact(n: Int): BigInt =
if (n == 0) 1 else fact(n-1) * n
class Factorizer(n: Int) {
def ! = fact(n)
}
implicit def int2fact(n: Int) = new Factorizer(n)

println("10! = " + (10!))
}

Maps

/** Maps are easy to use in Scala. */
object Maps {
val colors = Map("red" -> 0xFF0000,
"turquoise" -> 0x00FFFF,
"black" -> 0x000000,
"orange" -> 0xFF8040,
"brown" -> 0x804000)
def main(args: Array[String]) {
for (name <- args) println(
colors.get(name) match {
case Some(code) =>
name + " has code: " + code
case None =>
"Unknown color: " + name
}
)
}
}

Implicits

/* Defines a new method 'sort' for array objects */
object implicits extends Application {
implicit def arrayWrapper[A : ClassManifest](x: Array[A]) =
new {
def sort(p: (A, A) => Boolean) = {
util.Sorting.stableSort(x, p); x
}
}
val x = Array(2, 3, 1, 4)
println("x = "+ x.sort((x: Int, y: Int) => x < y))
}

Match Arguments

/** Basic command line parsing. */
object Main {
var verbose = false

def main(args: Array[String]) {
for (a <- args) a match {
case "-h" | "-help" =>
println("Usage: scala Main [-help|-verbose]")
case "-v" | "-verbose" =>
verbose = true
case x =>
println("Unknown option: '" + x + "'")
}
if (verbose)
println("How are you today?")
}
}

Primes

/** Print prime numbers less than 100, very inefficiently */
object primes extends Application {
def isPrime(n: Int) = (2 until n) forall (n % _ != 0)
for (i <- 1 to 100 if isPrime(i)) println(i)

}

Sum Arguments

object Main {
  def main(args: Array[String]) {
try {
val elems = args map Integer.parseInt
println("The sum of my arguments is: " + elems.foldRight(0) (_ + _))
} catch {
case e: NumberFormatException =>
println("Usage: scala Main <n1> <n2> ... ")
}
}
}

Varargs

/** Using Java varargs */
object varargs extends Application {
val msg = java.text.MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet {0}.",
"Hoth", new java.util.Date(), "a disturbance in the Force")
println("Message="+msg)
}

아무래도 윈도우 용이겠죠? :)?

다음과 같이 실행해 보세요 ^^

> mkdir classes
> scalac -d classes %SCALA_HOME%\doc\scala-devel-docs\scala\examples\sort.scala
> scala -cp classes examples.sort
[6,2,8,5,1]

[1,2,5,6,8]

다음화에서 고급용으로 ^^