Skip to content

Instantly share code, notes, and snippets.

@humanscape-david
Last active July 1, 2020 05:55
Show Gist options
  • Select an option

  • Save humanscape-david/e050f6b4c914766290947d0c5c503bc3 to your computer and use it in GitHub Desktop.

Select an option

Save humanscape-david/e050f6b4c914766290947d0c5c503bc3 to your computer and use it in GitHub Desktop.
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