通过地图递归

时间:2013-10-14 21:34:25

标签: scala recursion map

我如何通过地图递归?

我正在寻找类似于列表递归的东西,如下所示。

def count(list: List[Int]): Int = { 
   def go(list: List[Int], acc: Int)) = {
      case x :: xs => go(xs, x + sum)
      case Nil => sum
   }
   go(list, 0)
}

请忽略foldreduce可在此处使用的事实。我提到这个尾递归函数作为我想要通过地图递归的样本。我希望能够在通过地图递归时附加到accumulator参数。

1 个答案:

答案 0 :(得分:0)

您可以使用.toSeq或.toList或类似方法将地图转换为Seq,或者您可以定义自己的地图提取器,但最简单的方法是直接使用头部和尾部。

def recursive[A, B](map: Map[A, B]): Int = 
  if (map.isEmpty) 0 else helper(map)

def helper[A, B](map: Map[A, B]): Int = (map.head, map.tail) match {
  case ((a, b), xs) if xs.isEmpty => 1
  case ((a, b), xs) => 1 + helper(xs)
}