【问题标题】:Why the inner function used in below scala code , cant we write it without the inner function为什么在下面的scala代码中使用内部函数,我们不能在没有内部函数的情况下编写它
【发布时间】:2019-01-17 18:45:36
【问题描述】:
def pack[A](l: List[A]):List[List[A]] = {
    def _pack(res: List[List[A]], rem: List[A]):List[List[A]] = rem match {
        case Nil => res
        case h::tail if (res.isEmpty || res.last.head != h) => _pack(res:::List(List(h)), tail)
        case h::tail => _pack(res.init:::List(res.last:::List(h)), tail)
    }
    _pack(List(),l)
}

以上代码将列表元素的连续重复项打包到子列表中。

【问题讨论】:

  • 因为这就是尾递归。

标签: scala function functional-programming nested


【解决方案1】:

内部功能似乎只是一种设计选择。由于使用了内部函数,可以在 pack[A] 范围内关闭整个实现。将 _pack 函数移到外面是绝对有效的(它需要添加一个通用参数),但是可以在 pack[A] 范围之外调用它。

这是上述功能的另一种可能实现:

def pack[A](l: List[A]) : List[List[A]] = (l :\ List.empty[List[A]]){
    case (e, (acc@(hd::_))::tl) if hd == e => (e::acc)::tl
    case (e,  acc)                         => List(e)::acc
}

【讨论】:

    猜你喜欢
    • 2018-09-22
    • 2021-03-22
    • 1970-01-01
    • 2017-11-04
    • 2021-06-24
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    相关资源
    最近更新 更多