Scala 49

Scala의 암시(implicit)

스칼라의 암시는 크게 두 가지의 방법으로 쓰인다. 1. 암시적 파라미터(암시적 인자)메소드의 파라미터에 implicit 키워드를 사용하는 방법이다.이미 implicit 키워드를 이용해 선언한 값이 존재할 때 그 값을 쓰게 된다. implicit val x: Int = 500 def plusValue(paramX: Int)(implicit paramY: Int) = paramX + paramY println( plusValue(100)(200) ) // 300 println( plusValue(200) ) // 700 이런 사용은 Future를 사용할 때를 생각하면 편하다.ExecutionContext가 필요한 Future 함수는 두번째 인자로 ExecutionContext를 입력받는다.* @param e..

Scala 2017.03.16

Java의 Comparator/Comparable, Scala의 Ordered/Ordering

자바에서는 비교 가능한 클래스의 구현을 위해 두 가지 인터페이스를 사용한다. 첫 번째로 자바빈 클래스에 구현해 '다른 객체와 비교' 하는데 사용하는 Comparable다.public class Fruit implements Comparable { public String name; public int price; public Fruit(String name, int price) { this.name = name; this.price = price; } @Override public String toString() { return this.name + " " + this.price; } @Override public int compareTo(Fruit that) { return this.price - th..

Scala 2017.03.15

P93. Scala로 풀어본 Arithmetic Puzzle

P93 (***) An arithmetic puzzle.Given a list of integer numbers, find a correct way of inserting arithmetic signs (operators) such that the result is a correct equation. Example: With the list of numbers List(2,3,5,7,11) we can form the equations 2-3+5+7 = 11 or 2 = (3*5+7)/11 (and ten others!). 리스트로 주어진 수의 사이에 '=' 를 넣어 양 쪽 식의 값이 같게 되는 경우를 찾는 문제다.List(2, 3, 5, 7, 11)을 입력했을 때 답의 일부는 아래와 같다.2 = (3 ..

P91. Scala로 풀어본 Knight's Tour(기사의 여행)

P91 (**) Knight's tour.Another famous problem is this one: How can a knight jump on an N×N chessboard in such a way that it visits every square exactly once?Hints: Represent the squares by pairs of their coordinates of the form (X, Y), where both X and Y are integers between 1 and N. (Alternately, define a Point class for the same purpose.) Write a function jumps(N, (X, Y)) to list the squares t..

Scala로 만들어본 Merge Sort

머지 소트(병합 정렬) 역시 강력하고 쉬운 알고리즘이다.절반으로 계속 나누어 나가다가 더 이상 나눌 수 없어지면 다시 합치는 알고리즘이다. 단지 합칠 때 작은 값과 큰 값의 순서를 확인하면서 합쳐나가는 것이 포인트다. 퀵 소트와 마찬가지로 절반으로 나누어 재귀호출하기 때문에 로그단위의 복잡도를 가진다.하지만 퀵 소트와는 다르게 이미 정렬된 값은 순서 그대로 합쳐져 stable한 결과를 가진다. 위키백과의 그림을 참고해 설명하자면 이렇게 두 단계로 나눌 수 있다. 노란 색으로 표시한 두 배열을 합치는 방법을 좀 더 자세히 보면 이런 순서가 된다.합칠 값 두개를 비교한 후 더 작은 값을 새로 만들 배열에 넣고, 나머지 값을 재귀호출 하는 것이다. 스칼라 코드로 구현하면 아래처럼 될 것이다.def mergeS..

Scala 2017.02.28

Scala로 만들어본 Quick Sort

퀵소트는 아주 강력하고 쉬운 정렬 알고리즘이다.배열의 값 하나를 선택해서(pivot), pivot보다 작은 것을 왼쪽, pivot보다 큰 것을 오른쪽으로 모은 후 왼쪽에 대한 재귀호출, pivot, 오른쪽에 대한 재귀호출 셋을 순서대로 이어붙이면 된다.함수가 호출될 때마다 피벗의 위치가 확정되고 재귀호출되어 재실행되는 리스트는 이전 배열의 절반 수준이기 때문에 복잡도를 로그단위로 끌어내릴 수 있다. 함수형 프로그래밍 언어들에서는 그 특유의 콤비네이터들이 있어 구현을 굉장히 쉽게 만든다.구글링으로 가장 먼저 볼 수 있는 스칼라 퀵 소트의 알고리즘은def quickSortHead[A](lst: List[A])(implicit ord: A => Ordered[A]): List[A] = lst match{ ca..

Scala 2017.02.28

Scala trait과 Java interface에서의 변수

자바는 자바8이 되며 default 키워드가 생겼고, 덕분에 인터페이스에도 메소드 바디 구현이 가능해졌다.스칼라의 trait과 거의 같다고 볼 수 있게 된 것이다. 하지만 trait과 interface에는 아직 차이가 많다. 그 중 하나는 자바 인터페이스에서의 변수는 static final이라는 것이다.interface DogImpl { String color = "Black"; String bark(); } class Dog implements DogImpl{ public String setColor(String newColor) { color = newColor; // 에러 return color; } public String getColor() { return color; } @Override pu..

Scala 2017.02.24

Scala의 static, companion object

스칼라는 자바와 다르게 static 키워드가 없다. 대신 비슷한 역할을 할 수 있게 클래스와 같은 이름을 가지는 object를 만들 수 있다.이렇게 만들어진 object를 companion object(동반 객체)라고 하고 같은 이름을 가진 클래스를 companion class(동반 클래스) 라고 한다. class Dog(name: String) { def bark = println("bark! bark!") def getName = name } object Dog { def apply(name: String) = new Dog(name) }object안에 필드나 메소드를 구현해 자바에서 static 키워드를 사용한 것과 같이 사용할 수 있다.또, 위와 같이 apply 메소드를 구현해 new 키워드 없이..

Scala 2017.02.24