Created
March 11, 2019 12:45
-
-
Save developer-sdk/b82fdaa17e5be1baa9803c2aca83d515 to your computer and use it in GitHub Desktop.
스칼라 메모아이즈 샘플, scala memoize, 함수 데이터 캐싱
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| object memoizeSample extends App { | |
| // 처리 시간 출력 | |
| import java.util.concurrent.TimeUnit.NANOSECONDS | |
| def time[T](f: => T): T = { | |
| val start = System.nanoTime() | |
| val ret = f | |
| val end = System.nanoTime() | |
| println(s"Time taken: ${NANOSECONDS.toNanos(end - start)} nonos") | |
| ret | |
| } | |
| // Map에 함수데이터 캐싱 | |
| def memoize[A, B](f: A => B) = new (A => B) { | |
| val cache = scala.collection.mutable.Map[A, B]() | |
| def apply(x: A): B = cache.getOrElseUpdate(x, f(x)) | |
| } | |
| // 피보나치 함수 | |
| def fibo(x: Int): Int = { | |
| if (x <= 2) | |
| 1 | |
| else | |
| fibo(x - 2) + fibo(x - 1) | |
| } | |
| // 캐싱 | |
| def memoFibo = memoize(fibo) | |
| for(x <- 1 to 10) | |
| println(time(memoFibo(30))) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment