'Scala'에 해당되는 글 12건

  1. 2016.05.11 List 1
  2. 2016.04.22 (싱글턴) Object
  3. 2016.03.16 scala 실행
  4. 2016.03.16 object,class,trait 접근성.
  5. 2016.03.15 scala Collections
  6. 2016.03.02 DB with anorm
  7. 2016.02.01 Scala OO Example
  8. 2015.07.27 scala 동기화 에러 방지 예제
  9. 2015.07.22 scala 문법 요약
  10. 2015.07.18 Functional Programming How?
  11. 2015.06.24 EOP
  12. 2015.06.08 Scala 특징

List

scala 2016. 5. 11. 09:07

특성

1. immutable    (Array는 mutable)

2. recursive 지원 (Arrary는 미지원)

3. covariant  -   if S is subtype of T이면   List[S]도 List[T]의 subtype.

     =>  이로 인해, List() (List[Nothing])  이 List[S나 T]의 subtype 이 된다.

 

head와 tail

  - head는 첫 아이템이고 tail은 나머지 모든 아이템.

 

List 생성

 $ val abc: List[String] = List("a","b","c")

 $ val fruit = "ora" :: "pea" :: "apples" :: Nil     (이 경우에는 Nil이 꼭 필요)

 

패턴지정 (위에서 fruit가 지정되어 있는 경우)

 $ val List(a,b,c) = fruit     이런형태로 지정해서 a,b,c 를 자동 입력도 가능 (a="ora"가 됨)

 

:: (cons 연산자)

 - scala내의 class로도 존재하고, List내의 method로도 존재.

   (class로 존재하기 때문에  x :: xs 가 ::(x,xs) 로 취급됨.

 

 

 

 

 

Posted by yongary
,

(싱글턴) Object

scala 2016. 4. 22. 18:29

scala 싱글턴 Object  (즉, 키워드 object)

는 2가지 용도로 쓰인다.




1.  Companion Object

- scala class에는 static 함수를 포함할 수 없기 때문에, class 와 동일한 Object 이름을 이용해서

static 함수를 모아 놓는다. 


class A(msg:String){

   def greet() = println(msg)

}


object A{

  def trim(s:String) = s..blabla

}



2. stand-alone Object.    

 - 이건 제일 자주보는 main을 포함하기 위한 용도이다.

object myApp {

  def main( args: Array[String]) {

     

  }

}


Posted by yongary
,

scala 실행

scala 2016. 3. 16. 09:33

  hello.scala 내용:  println(" Hello world")


1. hello.scala와 같은 script 작성 후  


$ scala hello.scala 로 실행 .



2. class나 object .scala작성후


$scalac co.scala

$scala co   

하면 되는데


scalac 보다 빠른 fsc (fast scala compiler)가 존재한다.

차이점은 fsc는 항상 메모리에 띄워 놓고, scalac은 JVM을 그 때 그때 띄우게 되는데..

따라서 fsc를 죽이고 싶다면 

$ fsc co.scala

$ scala co 

$ fsc - shutdown  으로 죽이면 된다.

Posted by yongary
,

class

- java의 class와 동일하다고 보면 되나, primary 생성자는 없다.

- primary 생성자는 class Dog(legs:Int, name:String){ } 로 정의에서 끝난다.

=> legs,name은 val로 자동생성된다.

- primary생성자의 body는 class 안에 아무데나 쓰면 된다.

- overload 생성자는 def this(legs:Int)와 같은식으로 명시하면 된다.


object

- companion object와 stand_alone object 가 존재한다.

- companion object는 java의 static함수를 모아놓은 것이라고 생각하면 된다.
  동일한 이름의 class가 존재한다.

- stand alone object는 독립적으로 존재하는데 보통
  def main(args:Array[String]) {  } 을 포함하는 용도로 사용된다. 


trait

- java의 interface와 유사하다고 보면되나, implements 키워드 대신 항상 extends키워드를 쓴다.

- method를 구현할 수 있다. (java Interface도 원래는 abstract함수만 되나, 1.8부터 body구현 지원)

- 인스턴스 생성시에 with 키워드로 바로 적용이 가능하다. (복잡하겠군요.. 인스턴스마다 다른 특성을 지니겠네요)


- extends Trait  해서 함수 오버라이드 시에..  def 앞에 override 키워드 꼭 필요.




class 인스턴스의 접근성

- class Dog{ var sum=0 }  일 경우 val a = new Dog 이 안됨.  단 var a일 경우.. a.sum+=1 은 됨.  

- class Dog{ private sum=0} 일 경우 val a = new Dog이 됨. s.sum +=1 이 안됨.

  

def의 접근성. =이 type을 의미함.

scala> def h = {"hello"}    h는 hello String 리턴.

scala> def g {"hello"}    g는 리턴없음. 즉 Unit리턴.

scala> def f:Unit = "hello"    g와 동일. 

Posted by yongary
,

scala Collections

scala 2016. 3. 15. 17:16

Array: mutable이고  java와 달리, (0),(1)로 마치 함수호출 하듯이 element get함.


List : immutable이고 동일한 type을 보관

tuple: immutable이고 서로 다른 type의 데이타를 저장할 수 있다. 


HashSet, HashMapt: mutable   (Set,Map은 trait임)

예) val s = new HashSet[String] 

    s += "AA"

예) val m = new HashMap[Int, String]

    m += (1 -> "Go to Hell") 


<immutable Set/Map> - factory method방식으로 이용가능.

    예) val s = Set("A", "BB", "CC")            : compoiler transfers as Set.apply()

   예) val s = Map(1 -> "AA", 2->"BB")       : compoiler transfers as Map.apply()




요약하면 immutable List,Tuple,  Set,Map이 존재한다.



Posted by yongary
,

DB with anorm

scala 2016. 3. 2. 16:58

scala에서 DB를 연동할 때, JDBC를 직접 사용할 수도 있지만

Play Framework와 함께 할때는 Anorm을 사용하는 방법이 편리하다.


REF-SITE :play



사용모습을 보면 아래와 같다.



(예제: 출처 https://janhelwich.wordpress.com/tag/anorm/ )

object Post{
  val parser = {
      get[String]("title") ~
      get[Date]("posted") ~
      get[String]("content")~
      get[Pk[Int]]("authorId") map {
      case title ~ posted ~ content ~ author => Post(title,  posted, content, User.findBy(author))
    }
  }
 
  def findAll() = {
    DB.withConnection {
      implicit connection =>
        SQL("select * from posts").as(parser *)
    }
  }
 
  def create(post: Post): Unit = {
    DB.withConnection {
      implicit connection =>
        SQL("insert into posts(title, posted, content, authorId) values ({title}, {posted}, {content}, {authorId})").on(
          'title -> post.title,
          'posted -> post.posted,
          'content -> post.content,
          'authorId -> post.author.id
        ).executeUpdate()
    }
  }


Posted by yongary
,

Scala OO Example

scala 2016. 2. 1. 10:52

Scala를 이용해서 OO를 TEST.

(OO Test using Scala)

object Seminar{


class Dog(a:Int, n:String){
var age:Int = a
var name:String = n

def feed()={
println(this.name+ ":eating dog food")
}
}


class Cat(a:Int, n:String) extends Dog(a:Int, n:String){
override def feed()={
println(this.name+ ":eating Cat food")
}
}


//////// MAIN ////////////////////////////////////////////////
def main(args:Array[String]) = {
var allDog:Array[Dog] = Array( new Dog(1,"dogA"),
new Dog(2,"dogB"),
new Dog(3,"dogC"),
new Dog(4,"dogD"),
new Cat(5,"catA"))


for( dog<- allDog)
dog.feed()

}
} //end
Posted by yongary
,

전통적인 consumer/supplier 예제를 간단히 변형해서

2개의 은행에서 각자 고객 수자를 관리하다가

전체 고객의 합을 구하는 형태를 문제가 있게 OLD한 방법으로 일부러 작성해보면 다음과 같다.

 

 

///////////////////////////////////////////////////////////////

class Bank {
var numKid:Int = 0
var numAdult:Int = 0
var numAged:Int = 0

def addNum (k:Int,a:Int,g:Int) = {
numKid += k
numAdult += a
numAged += g
Main.totalKid += numKid //no need on FP
Main.totalAdult += numAdult
Main.totalAged += numAged
}

}

////global FOR: Bank Sum total : OLD ///////////////
var totalAll:Int = 0 //NO NEED on FP
var totalKid:Int = 0
var totalAdult:Int = 0
var totalAged:Int = 0

 

// main
def main(args:Array[String]) = {


//// Bank Sum total :OLD ///////////////
val actorBank1 = actor {
val bank1 = new Bank
while (true) {
bank1.addNum(0, 1, 0)
Thread.sleep(10)
}
}

val actorBank2 = actor {
val bank2 = new Bank
while (true) {
bank2.addNum(2, 2, 1)
Thread.sleep(10)
}
}

//WHEN WANT TO PRINT
while (true) {
//SUM
Main.totalAll = Main.totalKid + Main.totalAdult + Main.totalAged //SUM

//NO MATCH?
if( totalAll != (totalKid+totalAdult+totalAged))
println("total:" + totalAll + ", Kid:" + totalKid + ", Adult:" + totalAdult + ", Aged:" + totalAged)

Thread.sleep(20)
}

 

 

 

이게 돌다보면 totalALL합이 맞지 않는 경우가 자주발생하도록 한 코드인데..

FP 스타일로 바꿔보면 다음과 같다.

 

 

 

================================> FP Style 로 전환

 

 

1. 가능하면 tuple을 이용

2. 전체적인 합 같은 totalAll 같은 변수를 아예 없앤다.

(그 외에 좀 더 sum2Bank같은 함수를 sum리턴안하게 좀 하고 싶은데.. 연구 중.)

 


class Bank {
var numKAG = (0,0,0)

def addNum (k:Int,a:Int,g:Int):Unit = {
numKAG = (numKAG._1 + k, numKAG._2 + a, numKAG._3 + g)
}
}

def sum2Bank (b1:Tuple3[Int,Int,Int], b2:Tuple3[Int,Int,Int] ) = {
val sum = ( b1._1 + b2._1, b1._2 + b2._2, b1._3 + b2._3 )
sum
}

def main(args:Array[String]) = {

//// Bank Sum total :OLD ///////////////
val bank1 = new Bank
val bank2 = new Bank

val actorBank1 = actor {
while (true) {
bank1.addNum(0, 1, 0)
Thread.sleep(10)
}
}

val actorBank2 = actor {
while (true) {
bank2.addNum(2, 2, 1)
Thread.sleep(10)
}
}


//WHEN WANT TO PRINT
while (true) {
//SUM
val sum = sum2Bank(bank1.numKAG, bank2.numKAG)
val totalAll = sum._1 + sum._2 + sum._3

//Always MATCH cause there is no toalALL variable
if( totalAll != (sum._1 + sum._2 + sum._3))
println("total:" + totalAll + ", Kid:" + sum._1)


Thread.sleep(20)
}


}

 

 


 


Posted by yongary
,

scala 문법 요약

scala 2015. 7. 22. 18:22

참고사이트:

 

var (x,y,z) = (1,2,3)    //튜플 선언

(1 to 5).map( 2 * )     // Vector(2,4,6,8,10)임.   2 * _ 에서 마지막에 _은 생략 가능    

import java.util.Date    //java도 import 해서 사용가능

1 :: List(2,3)             // List(1,2,3) 과 동일  연결연산자cons

 

(1 to 5)         // Range(1, 2, 3, 4, 5)

(1 until 6)       // Range(1, 2, 3, 4, 5)

(1 to 10 by 2)  // Range(1, 3, 5, 7, 9)

 

_ > 4             // v => v > 4 와 같은 predicate 임.

 

 

Posted by yongary
,

Functional Programming How?

scala 2015. 7. 18. 11:27

<FP 기법>

1. carry Over  :  tail recursive 처럼 결과값을 계속 넘기는 방식. (carry Over: 그냥 영어임.)  

2. predicate : 함수는 f()로 표현. Boolean을 리턴하는 함수는 predicate 이라고 부름.
       (이것도 scala에선 그냥 영어임. java엔 Predicate존재) 

=> p()를 이용해  함수 input  param들을 필터처럼 거를 수 있음

 

 

<FP기법 예제 - 1.carryOver>


object Main{

  def total(list: List[Int]) = { //기존 sum함수
    var sum = 0
    for (i <- list) { sum += i }
    sum
  }

  def totalFP(list:List[Int]) = { //부분합을 계속 넘기면서 합을 해나가는 방식.  foldLeft함수가 첫번째 param으로 carryOver로 계속 받아 주면서 iterate를 제공.
    list.foldLeft(0) { (carryOver,v) => carryOver + v }
  }

  def main(args:Array[String]) = {
    println(totalFP(List(1,2,3,4,5)))
  }
}

 

 

<FP기법 예제 - 2.Predicate>

def totalFP(list:List[Int] , p:Int => Boolean) = {
list.foldLeft(0) { (carryOver,v) => if (p(v)) carryOver + v else carryOver }
}

def main(args:Array[String]) = {
println(totalFP(List(1,2,3,4,5),{ v => v % 2 == 0 })) //짝수인 2,4 만 적용되서 합이 6 이 나옴.
}

추가적으로 v => v > 4 같은 predicate은 _ > 4 로 표시 가능

 

 

그리고 아래 3가지들이 scala에서 좀 특별하다.

trait -  java의 Interface와 비슷하지만, class특성도 지님.

   <trait특성 >

     - extends 로도 with 로도 사용가능하다. 심지어는 구현body가 존재해도 된다.

     - with의 경우에는 여러가지 trait가 사용가능하며, with A, with B의 경우 B가 먼저 적용된다.

     - override abstract라는 키워드를 사용하여 기존 def를 추상화하여 사용할 수도 있다.

     - Class 가 아니고 인스턴스에도 사용가능 : with Friends

 

xml - xml이 1등급 고객임. "" 필요없음

actor - thread + 큐 : 수천개의 actor를 만들어도 된다


자세한 건 여기클릭: hillarious indian guy

 

 

Posted by yongary
,

EOP

scala 2015. 6. 24. 08:59

scala로 EOP (Expression Oriented Programming)을 하기에 좋다.

 

 

http://alvinalexander.com/scala/best-practice-think-expression-oriented-programming-eop 

Posted by yongary
,

Scala 특징

scala 2015. 6. 8. 15:52

<<

JAVA:  bytecode는 interpre언어이나.. 실행시 JIT Compiler가 기계어로 바꿔서 실행하므로 compile언어라고 본다.

Scala는 이와 동일하게 javabytecode로 바꾸는 방식을 그대로 따르며, 완전한 java bytecode를 이용한다.   >>

 

 

이름에서 나와있듯이 scalable한 언어이다.

 

아래 1번 scalable이 6번 안전성과 관계를 좀 더 살펴봐야 할 것 같은데

어쨌던 Functional 언어의 등장 자체가

multi-core에서 안전성을 가지기 위해서 이므로..

6번의 안전성을 기반으로 1번 확장성도 가지게 된다고 개인적으로 보고 있다.

 

 

 

<Scala의 특징>

 

1. scalable

 

2. pure Object-Oriendted  (java는 primitive가 Object가 아님)

3. Functional 언어

- Assignment를 없애서, 참조투명성(REFERENTIAL TRANSPARENCY) 을 확보.

참고사이트:

4. Java 호환.

5. 함수도 객체.

 

6. future-Proof

 

7.Fun 

참고사이트:




한글 튜토리얼


< 기본 문법>

def : function이나 method를 선언할때 사용 

val : reasign이 불가능한 상수를 선언할때 사용 

var: reasign이 가능한 변수를 선언할때 사용 


exam )

    def helloWorld = println("hello world.") 

    val foo: Int = 1 

    var bar = "test" 


<case Class>

new 없이 쓸 수 있고,  getter필요없이 바로 .value 로 access.

 

Several Example : http://alvinalexander.com/scala/ 

 

<Flat Map>

http://alvinalexander.com/scala/collection-scala-flatmap-examples-map-flatten 

Posted by yongary
,