안전을 위한 주의사항 - TBROAD · 2017-08-29 · smt-c5012 사용설명서_ 1 안전을 위한 주의사항 사용자의 안전과 재산상의 손해를 예방하기 위한
자바프로그래머를 위한 스칼라
-
Upload
jong-gook-bae -
Category
Software
-
view
412 -
download
2
description
Transcript of 자바프로그래머를 위한 스칼라
스프링 MVC 스터디 / 배종국2014-11-04
자바프로그래머를위한스칼라
1 설치하기
2 첫번째예제
3 자바와함께사용하기
4 모든것은객체다
5 클래스에대하여
6 케이스클래스&패턴매칭
7 트레잇에대하여
8 제네릭함
설치하기
4
01 홈페이지다운로드
http://www.scala-lang.org/download/
첫번째예제
6
02
object HelloWorld {
def main(args: Array[String]){
println("Hello, world!")
}
}
Hello World
7
02 컴파일& 실행하기
scalac HelloWorld.scala
컴파일하기
scala -classpath . HelloWorld
실행하기
자바와함께사용하기
9
03
import java.util.{Date, Locale}
import java.text.DateFormat
import java.text.DateFormat._
object FrenchDate {
def main(args: Array[String]) {
val now = new Date
val df = getDateInstance(LONG, Locale.FRANCE)
println(df format now)
}
}
French Date
df.format(now)
모든것은객체다
11
04 숫자도하나의객체다
1 + 2 * 3 / x
(1).+(((2).*(3))./(x))
1.+((2.*(3))./(x))
12
04 함수마저객체다
object Timer {
def oncePerSecond(callback: () => Unit) {
while (true) { callback(); Thread sleep 1000 }
}
def timeFlies() {
println("time flies like an arrow...")
}
def main(args: Array[String]) {
oncePerSecond(timeFlies)
}
} 인자를받지않고아무것도돌려주지않는모든함수C/C++ 에서의 void 와비슷
13
04 이름없는함수
object TimerAnonymous {
def oncePerSecond(callback: () => Unit) {
while (true) { callback(); Thread sleep 1000 }
}
def main(args: Array[String]) {
oncePerSecond(() =>
println("time flies like an arrow..."))
}
}
클래스에대하여
15
05Complex
class Complex(real: Double, imaginary: Double) {
def re() = real
def im() = imaginary
}
16
05 인자없는함수
object ComplexNumbers {
def main(args: Array[String]) {
val c = new Complex(1.2, 3.4)
println("imaginary part: " + c.im())
}
}
17
05Complex
class Complex(real: Double, imaginary: Double) {
def re = real
def im = imaginary
}
18
05상속과재정의
class Complex(real: Double, imaginary: Double) {
def re = real
def im = imaginary
override def toString() =
"" + re + (if (im < 0) "" else "+") + im + "i"
}
scala.AnyRef
케이스클래스 & 패턴매칭
20
06케이스클래스간단덧셈계산기만들기ex : 1+1 , (x+x)+(7+y)
abstract class Tree
case class Sum(l: Tree, r: Tree) extends Tree
case class Var(n: String) extends Tree
case class Const(v: Int) extends Tree
인스턴스를 생성 할 때 new 키워드를 생략 할 수 있다. 다른 말
로, new Const(5)라쓰는대신 Const(5)라쓰면된다.
생성자 파라미터들에 대한 getter 함수가 자동으로 정의된다. 다
른말로, 클래스 Const의인스턴스 c에 있는생성자파라미터 v의
값은 c.v로접근가능하다.
21
06케이스클래스간단덧셈계산기만들기ex : 1+1 , (x+x)+(7+y)
abstract class Tree
case class Sum(l: Tree, r: Tree) extends Tree
case class Var(n: String) extends Tree
case class Const(v: Int) extends Tree
함수 equals와 hashCode도공짜로 제공된다. 이함수들은레퍼런스
의 동일함 보다 구조의 동일함을 확인 하도록 구현되어 있다. 다른 말
로, 생성 된 곳이 다르더라도각각의 생성자 파라미터 값이 같다면 같
은것으로 여긴다.
22
05
abstract class Tree
case class Sum(l: Tree, r: Tree) extends Tree
case class Var(n: String) extends Tree
case class Const(v: Int) extends Tree
함수 toString에 대한 기본적 구현이 제공된다. 이 기본적인 구현은
“값이 생성 될 때”의 형태를 출력한다. 예를 들어 x+1의 트리 표현
을출력한다면 Sum(Var(x),Const(1))이된다.
케이스 클래스들의 인스턴스는 패턴 매칭을 통해 따로 사용 될 수
있다.
케이스클래스간단덧셈계산기만들기ex : 1+1 , (x+x)+(7+y)
23
06 패턴매칭
{ case "x" => 5 case "y" => 7 }
type Environment = String => Int
산술표현식을나타낼타입완성 (Tree, Sum, Var, Const)
Environment 를 정의하자. 어떻게???아래와같이 해시맵형태로만들어보자.스칼라에서는이렇게 간단하게정의 가능
Environment 는 type 키워드를 사용하여이렇게 정의하자“문자열이 오면정수형으로바꿔라” 라는의미
24
06 패턴매칭
def eval(t: Tree, env: Environment): Int =
t match {
case Sum(l, r) => eval(l, env) + eval(r, env)
case Var(n) => env(n)
case Const(v) => v
}
이제실제로계산하는함수를정의하자
요만큼이 match 키워드를 사용한패턴매칭
25
06 패턴매칭
def eval(t: Tree, env: Environment): Int =
t match {
case Sum(l, r) => eval(l, env) + eval(r, env)
case Var(n) => env(n)
case Const(v) => v
}
eval 을 Tree 의 하위클래스의멤버함수로 정의해도될것같은데??
그렇게 해도된다. 패턴매칭을 사용하느냐?멤버함수를 사용하느냐?는개발자취향문제!!!!
But! 확장성을고려한다면…
26
06 패턴매칭 .VS. 멤버함수
멤버함수를사용하면
단지 Tree에대한 하위클래스를새롭게 정의함으로
새로운노드를추가하기쉽다.
반면에 트리에대한새로운연산을추가하는 작업이 고되다.
새로운연산을추가하기위해서는 Tree의모든하위클래스를
변경해야하기때문이다.
패턴매칭을사용하면상황이 반대가된다.
새로운노드를추가하려면트리에대해패턴매칭을 수행하는
모든함수들을새로운노드도 고려하도록변경해야한다.
반면에새로운연산을추가하는것은쉽다.
그냥새로운독립적인함수를만들면된다.
27
06 패턴매칭
1. 더하기 표현식은좌변과 우변을더한것이다
2. 변수 v에대한심볼추출은우리가추출하기 원하는심볼과관련이
있다면 1이되고그외의경우 0 이된다
3. 상수에대한심볼추출값은 0 이다.
def derive(t: Tree, v: String): Tree = t match {
case Sum(l, r) => Sum(derive(l, v), derive(r, v))
case Var(n) if (v == n) => Const(1)
case _ => Const(0)
} 가드 : if 키워드 뒤에 오는표현식을뜻함, 추가조건 부여그밖의모든 경우
28
06 테스트코드작성
def main(args: Array[String]) {val exp: Tree = Sum(Sum(Var("x"), Var("x")), Sum(Const(7), Var("y")))val env: Environment = { case "x" => 5 case "y" => 7 }println("Expression: " + exp)println("Evaluation with x=5, y=7: " + eval(exp, env))println("Derivative relative to x:\n " + derive(exp, "x"))println("Derivative relative to y:\n " + derive(exp, "y"))
}
출력 결과 :
Expression: Sum(Sum(Var(x),Var(x)),Sum(Const(7),Var(y)))
Evaluation with x=5, y=7: 24
Derivative relative to x:
Sum(Sum(Const(1),Const(1)),Sum(Const(0),Const(0)))
Derivative relative to y:
Sum(Sum(Const(0),Const(0)),Sum(Const(0),Const(1)))
트레잇에대하여
30
07 트레잇(trait)
코드를가질수있는인터페이스
Scala 에서 클래스가트레잇을 상속한다면?
트레잇의인터페이스를구현하라
And 트레잇에 구현된모든코드 다 니꺼!!
31
07trait Ord객체들의순서를비교하는기능( < , <=, ==, !=, >, >= )< , == 만구현되면모든기능이구현됨
trait Ord {
def < (that: Any): Boolean
def <=(that: Any): Boolean = (this < that) || (this == that)
def > (that: Any): Boolean = !(this <= that)
def >=(that: Any): Boolean = !(this < that)}
Java 의 Comparable 인터페이스와같은것!
Ord 에는세가지관계식이기본으로구현하나는추상함수 ( < )
Any 는 Scala 의 최상위타입!!!Java 의 Object 타입과같으나 int, float 와같은기본타입의상위타입이라는점에서차이가있다.
구현된것
32
07class Date그레고리력의날짜를나타내는클래스(크기비교가능)< , == 만구현되면모든기능이구현됨
class Date(y: Int, m: Int, d: Int) extends Ord {
def year = y
def month = m
def day = d
override def toString(): String = year + "-" + month + "-" + day
override def equals(that: Any): Boolean =
that.isInstanceOf[Date] && {
val o = that.asInstanceOf[Date]
o.day == day && o.month == month && o.year == year
}
def <(that: Any): Boolean = {
if (!that.isInstanceOf[Date])
error("cannot compare " + that + " and a Date")
val o = that.asInstanceOf[Date]
(year < o.year) ||
(year == o.year && (month < o.month ||
(month == o.month && day < o.day)))
}}
같다
작다
< , == 만구현되면모든기능이구현됨
제넥릭함
34
08 제네릭
Java 1.5 에제네릭지원이부족하여여러가지문제발생(지우개문제)
제네릭이먼지알려면 여기 :
http://opentutorials.org/module/516/6237
지우개문제가먼지알려면 여기 :
http://newstars.tistory.com/33
제네릭함(Genericty) 이란
코드를타입에대하여파라미터화할수있는능력
35
08 링크드리스트만들어보기
[Java]
리스트의원소타입을뭐로 하지 ? Int, Double???
불가능그냥 Object 로퉁!
But, int, long, float 같은기본타입에서는정상동작하지않음
프로그래머님이알아서 해주세요.
[Scala]
제네릭 클래스와제네릭함수를 지원
36
08 링크드리스트만들어보기
[Java]
리스트의원소타입을뭐로 하지 ? Int, Double???
불가능그냥 Object 로퉁!
But, int, long, float 같은기본타입에서는정상동작하지않음
프로그래머님이알아서 해주세요.
[Scala]
제네릭 클래스와제네릭함수를 지원
37
08class Reference간단한데이터저장구조클래스
class Reference[T] {
private var contents: T = _
def set(value: T) { contents = value }
def get: T = contents
}
얘가 제네릭 하기위해쓰는타입파라미터,매크로문자같은거임요기조기막쓰임
은훼이크고필요한데서쓰임
38
08class Reference간단한데이터저장구조클래스
class Reference[T] {
private var contents: T = _
def set(value: T) { contents = value }
def get: T = contents
}
기본값이라는의미수타입이라면 0,Boolean 타입이라면 falseUnit 타입이라면 ()모든객체타입은 null
39
08object IntegerReferenceget 함수의리턴값을정수처럼사용하기위해별도의캐스팅이필요없다.
object IntegerReference {
def main(args: Array[String]) {
val cell = new Reference[Int]
cell.set(13)
println("Reference contains the half of " + (cell.get * 2))
}
}
감사합니다다음스터디는스칼라로??혹시관심있으신분