【问题标题】:How to remake function that group list to simple recursion?如何将该组列表的功能重新制作为简单递归?
【发布时间】:2019-04-14 21:42:27
【问题描述】:

我编写了按索引对列表元素进行分组的函数,第一个列表中的索引为奇数,甚至在第二个中。但我不知道如何通过简单的递归来实现它并且不会出现类型不匹配。

代码如下:

// Simple recursion
def group1(list: List[Int]): (List[Int], List[Int]) = list match {
  case Nil => (Nil, Nil)
  case head :: Nil => (List(head), Nil)
  case head :: tail => // how can I make this case?
}

group1(List(2, 6, 7, 9, 0, 4, 1))

// Tail recursion
def group2(list: List[Int]): (List[Int], List[Int]) = {
  def group2Helper(list: List[Int], listA: List[Int], listB: List[Int]): (List[Int], List[Int]) = list match {
    case Nil => (listA.reverse, listB.reverse)
    case head :: Nil => ((head :: listA).reverse, listB.reverse)
    case head :: headNext :: tail => group2Helper(tail, head :: listA, headNext :: listB)
  }
  group2Helper(list, Nil, Nil)
}

group2(List(2, 6, 7, 9, 0, 4, 1))

【问题讨论】:

  • 您尝试了什么导致类型不匹配?
  • 不要忘记在简单递归中添加headNext(如head :: next :: tail
  • @Bergi 如果我尝试像另一个简单的递归那样执行此功能: case head :: headnext :: tail => (head :: group1(List(tail.head)), headnext :: group1(tail.tail)) 它让我不匹配,因为我无法将 head 元素添加到 (_, _),抱歉,我不知道它是如何调用英语的。这个函数不正确,这里是关于idea的
  • 你不想group1 .head.tail .tail - 你只想group1(tail)。然后group1(tail) 将返回两个列表的元组。您需要在第一个前面加上 head,在第二个前面加上 headNext。使用临时变量,这样您只需调用一次group1(tail),这样您就可以将结果分成两个列表。

标签: scala function functional-programming


【解决方案1】:

您必须调用下一个递归,解包结果元组,将每个头元素预先附加到正确的List,然后重新打包新的结果元组。

def group1(list: List[Int]) :(List[Int], List[Int]) = list match {
  case Nil                => (Nil, Nil)
  case head :: Nil        => (List(head), Nil)
  case hdA :: hdB :: tail => val (lstA, lstB) = group1(tail)
                             (hdA :: lstA, hdB :: lstB)
}

【讨论】:

  • 谢谢,现在我明白了如何使用变量以防万一。但是不知道是不是还是函数式编程?还是这个变量不喜欢语句或命令式?
  • 这个group1() 方法创建了7 个变量。它们是(按顺序)listheadhdAhdBtaillstAlstB。它们中的每一个都是val(即不可变),因此它不会与函数式编程的原则相冲突。
  • 非常感谢您的解释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-19
  • 1970-01-01
  • 2014-05-18
  • 2022-01-20
相关资源
最近更新 更多