-
Notifications
You must be signed in to change notification settings - Fork 0
2_Getting_started_with_functional_programming_in_Scala
Torres edited this page Apr 30, 2019
·
1 revision
-
스칼라로 순수함수형 코딩을 해보자.
-
스칼라의 기본 문법?
- tail recursive function
- high order function
- polymorphic
object MyModule {
def abs(n: Int): Int =
if (n < 0) -n
else n
private def formatAbs(x: Int) = {
val msg = "The absolute value of %d is %d"
msg.format(x, abs(x))
}
def main(args: Array[String]): Unit =
println(formatAbs(-42))
}
- object object
- private keywork
- return type 표기 방법
scalac MyModule.scala
scala MyModule
- scala interpreter
- namespacs? 주소?
- module? 파티션?
- writing loops functionally
def factorial(n: Int): Int = {
def go(n: Int, acc: Int): Int =
if (n <= 0) acc
else go(n-1, n*acc)
go(n, 1)
}
- tail recursive
object MyModule {
...
private def formatAbs(x: Int) = {
val msg = "The absolute value of %d is %d."
msg.format(x, abs(x))
}
private def formatFactorial(n: Int) = {
val msg = "The factorial of %d is %d."
msg.format(n, factorial(n))
}
def main(args: Array[String]): Unit = {
println(formatAbs(-42))
println(formatFactorial(7))
}
}
- formatAbs, formatFactorial는 거의 비슷하지 않나?
- 그런데 high order function 같은건 왜 필요한가?
- 함수형 이름짓기란?? n이란 변수는 괜찮은가??
def findFirst(ss: Array[String], key: String): Int = {
@annotation.tailrec
def loop(n: Int): Int =
if (n >= ss.length) -1
else if (ss(n) == key) n
else loop(n + 1)
loop(0)
}
def findFirst[A](as: Array[A], p: A => Boolean): Int = {
@annotation.tailrec
def loop(n: Int): Int =
if (n >= as.length) -1
else if (p(as(n))) n
else loop(n + 1)
loop(0)
}
- 익명함수 사용하기?
- findFirst 예시
- 익명함수의 원래 정체는 뭐지? 왜 이상한 람다식만 적어도 잘 돌아가는거지?
- As you might have seen when writing isSorted, the universe of possible implementations is significantly reduced when implementing a polymorphic function
- partial function : 익명함수와 무엇이 다른가?
- composition function : 합성 함수