Last active
July 1, 2020 05:55
-
-
Save humanscape-david/e050f6b4c914766290947d0c5c503bc3 to your computer and use it in GitHub Desktop.
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
| fun main(args: Array<String>) { | |
| // compose를 사용하지 않은 합성 | |
| val powerOfTwo = { x: Int -> power(x.toDouble(), 2).toInt() } | |
| val gcdPowerOfTwo = { x1: Int, x2: Int -> gcd(powerOfTwo(x1), powerOfTwo(x2)) } | |
| println(gcdPowerOfTwo(25, 5)) // 25 출력 | |
| // 잘못된 합성 | |
| val curriedGcd1 = ::gcd.curried() | |
| val composedGcdPowerOfTwo1 = curriedGcd1 compose powerOfTwo | |
| println(composedGcdPowerOfTwo1(25)(5)) // 5 출력 | |
| // 적절한 합성 | |
| val curriedGcd2 = { m: Int, n: Int -> gcd(m, powerOfTwo(n)) }.curried() | |
| val composedGcdPowerOfTwo2 = curriedGcd2 compose powerOfTwo | |
| println(composedGcdPowerOfTwo2(25)(5)) // 25 출력 | |
| } | |
| fun gcd(m: Int, n: Int): Int = when (n) { | |
| 0 -> m | |
| else -> gcd(n, m % n) | |
| } | |
| fun power(x: Double, n: Int, acc: Double = 1.0): Double = when (n) { | |
| 0 -> acc | |
| else -> power(x, n - 1, x * acc) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment