【问题标题】:Implement higher order functions and lambda实现高阶函数和 lambda
【发布时间】:2021-08-03 00:59:58
【问题描述】:

我尝试向高阶函数添加一个 lambda 表达式。但我的问题是: 如何实现 forEach 函数,列表中的每个元素与传递 函数操作调用?

import java.lang.IndexOutOfBoundsException

    class LinkedList <T> {
        data class Node<T>(val data: T, var next: Node<T>?)

        private var first: Node<T>? = null


        fun addFirst(data: T) {
            val newNode = Node(data, first)
            first = newNode
        }

        fun isEmpty() = first == null

         fun clear(): Any {
           return LinkedList<T>().clear()
        }

        fun get(index: Int): Any {
            var position = 0
            var runPointer = first
            while (runPointer != null && position != index) {
                position += 1
                runPointer = runPointer.next
            }
            return runPointer?.data ?: throw IndexOutOfBoundsException()
        }

         
         
        fun forEach(action: (T) -> Unit) {  
            ...

        }
    }

【问题讨论】:

  • 与您实现get 的方式相同,但在runPointer.data 上调用action
  • 我同意@al3c,您只需对循环时遇到的每个runPointer.data 调用操作即可。另外,clear() 的合约是什么?这似乎真的很奇怪:它返回一个空列表,但对 this 列表没有任何作用。
  • 你能给我看每个函数的例子吗,因为它不适合我

标签: kotlin lambda higher-order-functions


【解决方案1】:

forEach 是标准库中 Iterable 的扩展函数

 fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
    for (element in this) action(element)
}

来源https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/common/src/generated/_Collections.kt

【讨论】:

  • 好的,谢谢,但是没有可迭代的我怎么能做到。我应该怎么写在这里 fun forEach(action: (T) -> Unit) {
  • 好吧,你可以在没有 Iterable 的情况下使用它,比如 fun forEach.. 但这仅适用于 LinkedList 类型,换句话说,你调用的变量必须是超类的子类
【解决方案2】:

当您使用first: Node 时,您应该这样做:

fun forEach(action: (T) -> Unit) {
    var p = first
    while (p != null) {
        action(p.data)
        p = p.next
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多