Tag: 递归

使用递归对ktolin进行阶乘的Stackoverflow错误

这是我的代码这使输出控制台上的堆栈溢出错误30次 fun main(args:Array<String>){ var no:Int=Integer.parseInt(readLine())//read input from user and convert to Integer var ans:Int=calculateFact(no) //call function and store to ans variable println("Factorial of "+no+" is "+ans) //print result } fun calculateFact(no:Int):Int //function for recursion { if(no==0) { return 1 } return (no*calculateFact(no)) } 我不知道什么是错误解决PLZ

如何在Kotlin中使用foldRight递归实现dropWhile

我一直在使用.foldRight()递归地实现高阶函数,就像实践一样,但是却一直难以实现。 _Collections.kt有迫切的方法,但我不能将其转换为递归结构。 作为参考,这是takeWhile fun takeWhile(list:List<Int>, func:(Int) -> Boolean):List<Int> = list.foldRight(emptyList(), { next:Int, acc:List<Int> -> if (func(next)) acc.plus(next) else emptyList() })

类型检查已经在kotlin中进行递归

val cycleRunnable = Runnable { handler.postDelayed(cycleRunnable,100) } 我得到错误错误:(219,29)类型检查已经遇到递归问题。 最简单的解决方法:明确指定声明的类型 但是它的确切的Java版本没有任何错误 private final Runnable cycleRunnable = new Runnable() { public void run() { handler.postDelayed(cycleRunnable, POST_DELAY); } };

如何避免Java / Kotlin / IntelliJ IDEA中的StackOverFlow错误?

我想做一个BigInteger的阶乘(在Kotlin中)。 有了尾递归,当我尝试做9000时,会出现StackOverFlow错误! 。 有了一个非递归函数,我可以做到这一点…但我很好奇如何避免这种错误。 这是我的代码: import java.math.BigInteger fun tail_recursion_factorial(n: BigInteger, factorialOfN: BigInteger = BigInteger.valueOf(2)): BigInteger { return when(n){ BigInteger.ONE -> BigInteger.ONE BigInteger.valueOf(2) -> factorialOfN else -> tail_recursion_factorial(n.minus(BigInteger.ONE), n.times(factorialOfN)) } } fun non_recursive_factorial(n: BigInteger): BigInteger{ var i: BigInteger = BigInteger.ONE var factorial: BigInteger = BigInteger.ONE while (i<=n){ factorial = factorial.times(i) i = i.plus(BigInteger.ONE) } return factorial […]

Kotlin:相互递归函数的尾递归

假设我写这样的代码: tailrec fun odd(n: Int): Boolean = if (n == 0) false else even(n – 1) tailrec fun even(n: Int): Boolean = if (n == 0) true else odd(n – 1) fun main(args:Array<String>) { // 🙁 java.lang.StackOverflowError System.out.println(even(99999)) } 我如何让Kotlin优化这些相互递归的函数,这样我就可以运行main而不抛出StackOverflowError了? tailrec关键字适用于单一函数递归,但没有更复杂的。 我也看到一个警告,就是在使用tailrec关键字的地方找不到tail-calls。 编译器也许这太难了?

Kotlin – 如何递归调用一个lambda函数

我试图从Kotlin重新实现linrec函数。 以下是目前在Kotlin中的样子: fun <A, B> linrec(indivisible: (List<A>) -> Boolean, value: (List<A>) -> B, divide: (List<A>) -> List<List<A>>, combine: (A, B) -> B ) : (List<A>) -> B { val myfunc: (List<A>) -> B = { input -> if (indivisible(input)) { value(input) } else { val split = divide(input) val left = split[0][0] val right = […]