Foggy day
Kotlin - recursive function -2 : TCE 본문
class KotlinPlayGroundActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kotlin_play_ground)
val lists = listOf('a', 'f', 'd', 'w')
println("toString : ${toString(lists)}")
println("add : ${add(10, 15)}")
println("addSecond : ${addSecond(10, 15)}")
println("factorialFirst : ${Factorial.factorialFirst(5)}")
println("FactorialSecond : ${FactorialSecond.factorialSecond(3)}")
println("factorialBigInteger : ${factorialBigInteger(BigInteger.valueOf(35))}")
}
fun toString(list: List<Char>): String {
tailrec fun toString(list: List<Char>, s: String): String =
if (list.isEmpty())
s
else
toString(list.subList(1, list.size), append(list[0], s))
return toString(list, "jh")
}
fun append(c: Char, s: String): String = "$s $c"
fun inc(n: Int) = n + 1
fun dec(n: Int) = n - 1
fun add(a: Int, b: Int): Int {
var x = a
var y = b
while (true) {
if (y == 0) return x
x = inc(x)
y = dec(y)
}
}
tailrec fun addSecond(x: Int, y: Int): Int =
if (y == 0)
x
else
addSecond(inc(x), dec(y))
object Factorial {
lateinit var factorialFirst: (Int) -> Int
init {
factorialFirst = { n -> if (n <= 1) n else n * factorialFirst(n - 1) }
}
}
object FactorialSecond {
val factorialSecond: (Int) -> Int by lazy {
{ n: Int ->
if (n <= 1) n else n * factorialSecond(n - 1)
}
}
}
fun factorialBigInteger(n: BigInteger): BigInteger =
if (n == BigInteger.ONE)
BigInteger.valueOf(1)
else
n * factorialBigInteger(n - BigInteger.ONE)
}
'Kotlin' 카테고리의 다른 글
Kotlin - Object Expressions (0) | 2021.04.08 |
---|---|
Kotlin - when, for (0) | 2021.04.06 |
Kotlin - recursive function -1 (0) | 2021.03.21 |
Kotlin - lambda expression -5 : using data class, value type (0) | 2021.03.21 |
Kotlin - lambda expression -4 : curried function (0) | 2021.03.21 |