backend/tests: add trivial tests for tailrec
This commit is contained in:
committed by
SvyatoslavScherbina
parent
9a28d648a8
commit
8427612d59
@@ -1207,6 +1207,7 @@ task initializers2(type: RunKonanTest) {
|
||||
"1\n" +
|
||||
"globalValue2\n" +
|
||||
"globalValue3\n"
|
||||
|
||||
source = "runtime/basic/initializers2.kt"
|
||||
}
|
||||
|
||||
@@ -1301,6 +1302,16 @@ task vararg_of_literals(type: RunKonanTest) {
|
||||
source = "lower/vararg_of_literals.kt"
|
||||
}
|
||||
|
||||
task tailrec(type: RunKonanTest) {
|
||||
goldValue = "12\n100000000\n" +
|
||||
"8\n" +
|
||||
"1\n" +
|
||||
"3 ...\n2 ...\n1 ...\nready!\n" +
|
||||
"2\n-1\n" +
|
||||
"true\nfalse\n"
|
||||
source = "lower/tailrec.kt"
|
||||
}
|
||||
|
||||
task inline4(type: RunKonanTest) {
|
||||
goldValue = "3\n"
|
||||
source = "codegen/inline/inline4.kt"
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
fun main(args: Array<String>) {
|
||||
println(add(5, 7))
|
||||
println(add(100000000, 0))
|
||||
|
||||
println(fib(6))
|
||||
|
||||
println(one(5))
|
||||
|
||||
countdown(3)
|
||||
|
||||
println(listOf(1, 2, 3).indexOf(3))
|
||||
println(listOf(1, 2, 3).indexOf(4))
|
||||
|
||||
println(Integer(5).isLessOrEqualThan(7))
|
||||
println(Integer(42).isLessOrEqualThan(1))
|
||||
}
|
||||
|
||||
tailrec fun add(x: Int, y: Int): Int = if (x > 0) add(x - 1, y + 1) else y
|
||||
|
||||
fun fib(n: Int): Int {
|
||||
tailrec fun fibAcc(n: Int, acc: Int): Int = if (n < 2) {
|
||||
n + acc
|
||||
} else {
|
||||
fibAcc(n - 1, fibAcc(n - 2, acc))
|
||||
}
|
||||
|
||||
return fibAcc(n, 0)
|
||||
}
|
||||
|
||||
tailrec fun one(delay: Int, result: Int = delay + 1): Int = if (delay > 0) one(delay - 1) else result
|
||||
|
||||
tailrec fun countdown(iterations: Int): Unit {
|
||||
if (iterations > 0) {
|
||||
println("$iterations ...")
|
||||
countdown(iterations - 1)
|
||||
} else {
|
||||
println("ready!")
|
||||
}
|
||||
}
|
||||
|
||||
tailrec fun <T> List<T>.indexOf(x: T, startIndex: Int = 0): Int {
|
||||
if (startIndex >= this.size) {
|
||||
return -1
|
||||
}
|
||||
|
||||
if (this[startIndex] != x) {
|
||||
return this.indexOf(x, startIndex + 1)
|
||||
}
|
||||
|
||||
return startIndex
|
||||
|
||||
}
|
||||
|
||||
open class Integer(val value: Int) {
|
||||
open tailrec fun isLessOrEqualThan(value: Int): Boolean {
|
||||
if (this.value == value) {
|
||||
return true
|
||||
} else if (value > 0) {
|
||||
return this.isLessOrEqualThan(value - 1)
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user