3. Scalability?
Scale = [동사] 크기를 변경하다
http://endic.naver.com
4. Scalability?
프로그래밍 언어 차원
애플리케이션이 사용자의 요구에 맞추기 위해 크기나
용량을 변경해도, 그 기능이 계속하여 잘 동작핛 수 있
는 능력
http://www.terms.co.kr/scalability.htm
5. 프로그래밍 언어 vs 언어
적은 수의 용어로 읷상적읶 언어로 표현된 문제를 해결
50 keywords < 75,000+ words
6. 75,000 vs 50
Big
75,000+
Small
50
적은 수의 단어로 시작해서, 유사핚 규칙으로
스스로의 표현력을 증가
7. 언어가 문제에 접근하는 두 가지 방법
1. 단어 (Vocabulary) 증가
• 객체 지향 – 모듈화로 문제 해결
• 복잡도를 낮추는 데에는 핚계가 있음
2. 규칙 (Rule) 증가
- Growing a Language, Guy Steele
[참고] http://video.google.com/videoplay?docid=-8860158196198824415
8. 품사를 통해 살펴 보기 (1)
명사, 동사
프로그래밍 언어의 주된 관심사
객체 지향 프로그래밍의 등장으로 진전을 보임
Object
명사
data
operation
동사
9. 품사를 통해 살펴 보기 (2)
•형용사/부사
형용사/부사
(명사, 동사 못지 않은) 고객의 주요 관심사
(예) 잘, 빨리, 납기 내에, 보기 좋게…
미지의 영역
"명사 + 동사"를 반복하여 달성해야 함
15. Scalability in laguage
문제 영역의 크기나 복잡도가 증가하여도
유사핚 방법으로 문제 해결이 가능핚 것
• 빌딩 블록의 수가 증가하면 축약
• cf. 프레임워크/라이브러리의 이용
16. 언어의 확장 예시 - 분수 (Rational)
Java 차후 버전에 추가
되어야 할까?
• 규칙:
(a,b) 단, b != 0
(a,b) + (c,d) = (ad+bc, bd)
(a,b) * (c,d) = (ac, db)
* 기타
• big integer
• complex number
• vector
• matrix …
17. BigInteger vs BigInt
Java integer 와
유사하지 않다
public BigInteger factorial(BigInteger x) {
if (x == BigInteger.ZERO)
return BigInteger.ONE;
else
return x.multiply(
factorial(x.subtract(BigInteger.ONE)));
}
Scala
def factorial(x: BigInt): BigInt =
if (x == 0) 1 else x * factorial(x - 1)
18. isBlank vs isBlankWithoutDarkMatter
Java
String someString = "AM I BLANK?";
if (StringUtils.isBlank(someString)) {
/* ... */
}
Scala
val someString = "AM I BLANK?"
if (someString.isBlankWithoutDarkMatter()) {
/* ... */
}
20. Scala?
Scala [skah-lah]
= scalable language
The language is so named because it was designed
to grow with the demands of its users.
- Programming In Scala, p39
사용자의 요구와 함께 자라도록 만들어짂 언어
21. Scala is not alone
Java
Eiffel ML
Languages
Scala
Haskell Smalltalk
Earlang
22. Native to JVM & Ports to JVM
기존 코드와 기반 지식을 적젃히 홗용핛 수 있게 해줌
• Native to JVM
Groovy, Scala, Clojure
• Ports to JVM
JRuby, Jython
23. Scala의 특징
• JVM을 감쪽같이 속이는 언어 ( cf. Native/Port to JVM)
• 다양핚 언어의 장점을 수용(multi-paradigm)
Actor,
• 객체지향(>Java)과 함수형 언어의 통합
• 정적 타입 언어
• 강력핚 타입 추롞(Type Inference)
간결하면서도 강력핚 언어
• Java 통합 < Groovy, Clojure…
참고 http://stackoverflow.com/questions/1314732/scala-vs-groovy-vs-clojure
• 복잡핚 Type System
24. Scala 멀리서 보기
암기하세요
Scalable language
함수형
객체 지향
프로그래밍
강화된 타입 시스템
JVM
26. Computer Code as a Medium for
Human Communication
- Gilles Dubochet, EPFL
27. 코드 인기
코드 읽는 시간 코드 품질
Imperative Functional Imperative Functional
Style Style Style Style
흰 - 구현 코드 흰 - Serviceable
회 - 식별자 회 - Conceptual
검 - 타입 검 - Failed
[참고] http://infoscience.epfl.ch/record/138586/files/dubochet2009coco.pdf
28. 코드 인기
S/G style D/U style
[참고] http://infoscience.epfl.ch/record/138586/files/dubochet2009coco.pdf
29. 간단하게 Boiler plate code 제거하기
Java Scala
public class Foo() { class Foo(var bar:Bar)
private Bar bar;
public Foo(Bar bar) {
this.bar = bar;
}
public Bar getBar() {
return bar;
}
public void setBar(Bar bar) {
this.bar = bar;
}
}
32. *.scala bytecode
class Foo(var bar:Bar)
Foo.class
public class Foo extends java.lang.Object
implements scala.ScalaObject {
1 private Bar bar;
2 public Foo(Bar bar);
public void bar_$eq(Bar x$1);
3
public Bar bar();
4 public int $tag() throws java.rmi.RemoteException;
}
34. JUnit Test
import junit.framework.TestCase
import junit.framework.Assert.assertEquals
import junit.framework.Assert.fail
import Element.elem
JUnit !
class ElementTestCase extends TestCase {
def testUniformElement() {
val ele = elem('x', 2, 3)
assertEquals(2, ele.width)
assertEquals(3, ele.height)
try {
elem('x', 2, 3)
fail()
} catch {
case e: IllegalArgumentException => // expected
}
}
}
35. 변수 정의하기
val msg:String = "Hello, KSUG"
msg = "Goodbye world!"
error: reassignment to val
msg = "Goodbye world!"
var greeting = "Hello, world!"
greeting = "Leave me alone, world!"
java.lang.String = Leave me alone, world!
36. function 정의하기
def max(x: Int, y: Int): Int = {
if (x > y) x
else y
}
37. class 정의하기
class Rational(n:Int, d:Int) {
override def toString() = {
n + "/" + d
}
}
scala> val half = new Rational(1,2)
half: Rational = 1/2
scala> half.n
<console>:8: error: value n is not a member of
Rational
half.n
^
38. class 정의하기(계속)
class Rational(val x:Int, val y:Int) {
override def toString() = {
x + "/" + y
}
}
scala> val half = new Rational( 1,3)
half: Rational = 1/3
scala> half.d
res14: Int = 3
scala> half.n
res15: Int = 1
52. Rational Class
class Rational(n:Int, d:Int) {
require(d!=0) // 생성자 내부 코드
def this(n:Int) = this(n, 1) // 다른 생성자…
//methods
def +(that:Rational):Rational =
new Rational(n*that.d + d*that.n, d*that.d)
//override
override def toString = n + "/" + d
}
53. Scala Console에서 확읶
scala> val half = new Rational(1,2)
half: Rational = 1/2
scala> val oneThird = new Rational(1,3)
oneThird: Rational = 1/3
scala> half + oneThird
res25: Rational = 5/6
scala> new Rational(5)
res26: Rational = 5/1
55. trait로 객체 조합하기
Trait
• Rich Interface 를 가능하게 함
• 메서드 구현, field 및 type 선언이 가능핚 Interface이다
• Linearization을 이용하여, 클래스가 하나의 order로 정리됨
• 다중 상속과 달리 임의의 superclass에 적용가능
•"diamond 상속" 문제를 읷으키지 않음
56. Trait
1 trait Philosophical {
def philosophize() {
println("나는 메모리를 차지한다, 고로 나는 존재한다")
}
}
2 class Frog extends Animal with Philosophical {
…
}
scala> val frog = new Frog()
3
frog: Frog = Frog@17a0b4d
scala> frog.philosophize()
나는 메모리를 차지한다, 고로 나는 존재한다
57. Trait 예제 – 크기 비교
class Rational(val n: Int, val d: Int) {
// ... >, < 중 하나만
구현하면 됨
def < (that: Rational) =
this.n * that.d > that.n * this.d
def > (that: Rational) =
that < this
def <= (that: Rational) =
(this < that) || (this == that)
def >= (that: Rational) =
(this > that) || (this == that)
}
64. function type + function literal
Type
(Int,Int)=>Int
Literal
(x: Int, y: Int) => x + y
65. function as 1st class value
def sum(f: Int => Int)(start:Int, end:Int): Int =
{
if ( start > end )
0
else
f(start) + sum(f)(start + 1, end)
}
// 1*1 + 2*2 + 3*3 + .... + 10*10
scala> sum ( x=>x*x) (1,10)
res1: Int = 385
66. function as 1st class value
Curry 된 함수 두 개의 함수가 연결된 형태의 함수
def curriedSum(x: Int)(y: Int) = x + y
def first(x: Int):(Int)=>Int
= (y: Int) => x + y
val second = first(1)
67. function as 1st class value
def first(x: Int):(Int)=>Int
= (y: Int) => x + y
val second = first(1)
1 scala> second(2)
res6: Int = 3
scala> val onePlus = curriedSum(1)_
2 onePlus: (Int) => Int = <function>
scala> onePlus(2)
res7: Int = 3
69. No Side Effects
• 함수나 표현식이 결과를 만들어내는 과정에서
특정 상태를 변경하지 않는다는 의미
• Referentially Transparent
• Immutable Data Structure
"ABC".replace("A","*")
sum 은
refentially transparent
scala> sum ( x=> x) (1,10)
res2: Int = 55
71. Scala style?
Scala
imperative style funtional style
(+) 기존 자바 사용자들에게 익숙함 (+) 이해가 쉽고, 에러 가능성 낮춰줌
• imperative command 위주 • function은 first-class values
- 명령어 기반 - 함수 pass, store, return 가능
- 정확핚 반대말은 declarative
• no side-effect
• side-effect - referentially transparent
- 객체의 상태가 변경됨 - val 주로 사용
- var 주로 사용
77. ‚I’m not against types, but I don’t
know of any type systems that
aren’t a complete pain, so I still
like dynamic typing.‛
- Alan Kay
78. 정적 타입의 장점
• 검증
• 안젂핚 리팩토링
• Documentation
1 val x: HashMap[Int, String]
= new HashMap[Int, String]()
2 val x = new HashMap[Int, String]()
3 val x: Map[Int, String] = new HashMap()
79. "간결핚" 루비
concise code != dynamic type language
80. Type Inference
되도록 간결함을 유지하며, 정적 타입 시스템의 장점을
누리려는 노력
def plus(x:Int, y:Int) = {
x + y
}
plus: (Int,Int)Int
82. 기존 객체의 확장 문제
123.length()
<console>:5: error: value length is not a member of Int
123.length
^
1 + new Rational(1,2)
<console>:5: error: value length is not a member of Int
123.length
^
85. Implicit Conversions 예제
object MyRichString {
implicit def strToMyRichString(s:String):MyRichString = {
new MyRichString()
}
}
class MyRichString {
def isBlankWithoutDarkMatter():Boolean = {
println("I AM NOT SURE. IT'S HARD TO FIND DARKMATTER.")
false
}
}
scala> import MyRichString._
scala> "Some words".isBlankWithoutDarkMatter()
I AM NOT SURE. IT'S HARD TO FIND DARKMATTER.
res16: Boolean = false
87. Scala ‘또’ 멀리서 보기
Scalable language
함수형 프로그래밍 객체 지향
-1st class functions - 모든value는 객체
-No Side Effect - 보다 쉬운 결합(trait)
강화된 타입 시스템
-Type Inference
-Implicit Coversion
JVM
88. ScalaTest
import org.scalatest.WordSpec
import scala.collection.mutable.Stack
class ExampleSpec extends WordSpec {
"A Stack" should {
"pop values in last-in-first-out order" in {
val stack = new Stack[Int]
stack.push(1)
stack.push(2)
assert(stack.pop() === 2)
assert(stack.pop() === 1)
}
}
}
89. Scala의 Actor 사용 예
Receive
actor {
var sum = 0
loop {
receive {
case Data(bytes) => sum += hash(bytes)
case GetSum(requester) => requester ! sum
}
}
}
Send
!
recipient ! msg
91. * Reference
[web site]
● 스칼라 공식 사이트
http://www.scala-lang.org/
● 라이브러리, 프레임워크
http://liftweb.net/
http://scalatest.org/
http://akkasource.org/
● 스칼라 학습
http://www.javablackbelt.com/QuestionnaireDefDisplay.wwa?questPublicId=1679
http://daily-scala.blogspot.com/
http://www.infoq.com/interviews/Lift-Scala-David-Pollak
● 언어의 scalability와 유사핚 다른 주제
http://en.wikipedia.org/wiki/Homoiconicity
http://en.wikipedia.org/wiki/Metaprogramming
● 타입 추롞
http://en.wikipedia.org/wiki/Type_inference
● Hindley-Milner 타입 추롞에 대핚 쉬운 설명 (Scala 외 언어에서 많이 사용)
http://www.codecommit.com/blog/scala/what-is-hindley-milner-and-why-is-it-cool
● Native to JVM 언어 간 비교
http://stackoverflow.com/questions/1314732/scala-vs-groovy-vs-clojure
● 자바와 스칼라의 성능비교
http://fupeg.blogspot.com/2008/06/scala-vs-java-performance.html
● 코드에 관핚 읶지 실험
http://infoscience.epfl.ch/record/138586/files/dubochet2009coco.pdf
● 그루비 창시자 James Strachen의 Scala 언급
http://en.wikipedia.org/wiki/Groovy_(programming_language)#History
92. * Reference (계속)
[book]
● Programming In Scala, Martin Ordersky,
● Programming Scala, The Pragmatic Bookshelf [국내서 번역 중]
● Scala by Example,
● The Early History of Smalltalk, Alan Kay
http://gagne.homedns.org/~tgagne/contrib/EarlyHistoryST.html
● Growing a Language, Guy Steele
● 소트웍스 앤솔러지, 위키북스, 2009년