Functional Programming Principles in Scala - Lists

5.1 More Functions on Lists 앞서 보았던 것과 추가로 List의 Method 몇가지를 더 보자. Sublists and element access xs.length - The number of elements of xs. xs.last - The list's last element, exception if xs is empty. xs.init - A List consisting of all elements of xs except the last one, exception if xs is empty. xs take n - A List consisting of the first n elements of xs, or xs itselft if it is shorter than n. xs drop n - The rest of…

Keep reading

Functional Programming Principles in Scala - Types and Pattern Matching

4.1 Functions as Objects Functions as Objects 지금까지 Scala의 numeric type과 boolean type이 보통 class와 동일하게 적용되는 것을 볼 수 있었다. 그럼 function에 대해서는 어떨까? 사실 Scala에서 function은 object로 다뤄진다. 따라서 function type A => B는 단지 아래와 같은 형태의 축약이라고 볼 수 있다. trait Function1[A, B] { def apply(x: A): B } 따라서 function은 apply method를 지닌 object로 볼 수 있다. 또한 Function2, Function3 등 22개 까지 parameter를 받을 수 있는 trait가 있다. Expansion of Function Values 아래와 같이 anonymous function이 있다면, (x: Int) => x * x 다음과…

Keep reading

Functional Programming Principles in Scala - Data and Abstraction

3.1 Class Hierarchies 이전까지 single class에 대해 여러 각도로 확인해보았다면, 지금부터 좀 더 일반화하여 class 간 hierarchy구조를 보자. Abstract Classes abstract class IntSet { def incl(x: Int): IntSet def contains(x: Int): Boolean } 위 class를 보면 각 method에 body가 없는 것을 볼 수 있는데, 만약 abstract를 제거하면 에러를 발생한다. 또한, body가 없기 때문에 new를 통해 class를 instance할 수 없다. 이렇게 class에 대해 추상적(abstractive)으로 정하는 것을 abstract class라고 한다. Class Extensions set을 이용하여 binary tree를 구현해보자. tree에 가능한 type은 1. empty set을 위한 tree와 2. integer 값을 가지며…

Keep reading

Functional Programming Principles in Scala - Higher Order Functions

2.1 - Higher-Order Functions Functional Language에서는 Functions을 first_class values로 다룬다. 따라서 function을 parameter나 결과값으로 돌려받을 수 있다(return). 이것은 프로그램을 구성할 때 유연한 방법을 제공하는데, function을 위와 같이 다루기위해 사용하는 경우를 higher order functions라고 한다. 아래의 경우를 보자. // sum of the integers between a and b def sumInts(a: Int, b: Int): Int = if(a > b) 0 else a + sumIns(a + 1, b) // sum of the cubes of all the integers between a and b def cube(x: Int): Int = x * x * x def sumCubes(a: Int,…

Keep reading

Functional Programming Principles in Scala - Functions & Evaluation

1.1 Programming Paradigms Paradigm: In science, a paradigm describes distinct concepts or thought patterns in some scientific discipline. 보통 프로그래밍에서 Paradigm이라고 말하는 것들은 다음과 같다. Imperative Programming Functional Programming Logic Programming 많은 사람들이 또하나의 Paradigm으로 이야기는 하지만, 위에 3가지를 합쳐 한 가지 더 이야기 할 수 있다. Object-orient Programming Imperative Programming Imperative Programming은 다음과 같은 성질을 가진다. modifying mutable variables using assignments and control structures such as if-then-else, loops, break, continue, return imperative programs을 이해하는 방법으로 폰 노이만 컴퓨터를 생각하면 되는데, 다음과 같은 유사점을 볼 수 있다. Mutable variables…

Keep reading