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 = myfunc(split[1]) // Error combine(left, right) } } return myfunc }
当我尝试运行代码时,IntelliJ给了我下面的错误:
Error:(40, 19) Kotlin: Unresolved reference: myfunc
我的问题是: 如何使自己的lambda函数调用?
你不要从里面调用lambda(“匿名函数”)。 这是什么功能:
fun <A, B> linrec(indivisible: (List<A>) -> Boolean, value: (List<A>) -> B, divide: (List<A>) -> List<List<A>>, combine: (A, A) -> B ) : (List<A>) -> B { fun myfunc(input: List<A>): B { // rearranged things here return if (indivisible(input)) { // added `return` value(input) } else { val split = divide(input) val left = split[0][0] val right = myfunc(split[1]) combine(left, right) // * } } return ::myfunc }
现在这正是你写的代码,但不能编译。 在标有*
kotlinc的行上,表示Type mismatch: inferred type is B but A was expected
。
PS我不知道代码在做什么,所以我只解决了你所问的编译错误。