在foldleft中使用collection.Map

时间:2017-07-14 17:33:53

标签: scala scala-collections

你可以使用collection.Map作为fold的累加器/返回值吗?

例如:

   using System.Xml;
    using System.Xml.Linq;
    using System.Xml.XPath;

public static List<XmlNode> queryXPath(this IXPathNavigable source, String xPath, XmlNamespaceManager nsManager = null)
    {
        XPathNavigator xNav = source.CreateNavigator();
        if (nsManager == null) nsManager = new XmlNamespaceManager(xNav.NameTable);
        List<XmlNode> output = new List<XmlNode>();
        XPathExpression xExp = XPathExpression.Compile(xPath, nsManager);
        XPathNodeIterator xIterator = xNav.Select(xExp);
        while (xIterator.MoveNext())
        {
            XmlNode tmp = xIterator.Current.UnderlyingObject as XmlNode;

            output.Add(tmp);
        }
        return output;
    }

Scala给出了以下类型错误:

Seq(1, 2, 3).foldLeft(collection.Map.empty[Int, Int]) { 
  case (map, i) => map.asInstanceOf[collection.Map[Int, Int]] + (i -> i)
}

为什么强制使用 found : scala.collection.Map[Int,Int] required: scala.collection.immutable.Map[Int,Int] Seq(1, 2, 3).foldLeft(collection.Map.empty[Int, Int]) { case (map, i) => map.asInstanceOf[collection.Map[Int, Int]] + (i -> i) } 代替collection.immutable.Map

编辑:毫无意义的演员有点误导,所以我想让我的意图更清晰。我在帖子中专门使用collection.Map,因为它是collection.Mapimmutable.Map的超类。实际上,我正在使用返回mutable.Map的折叠内部的函数,考虑:

collection.Map

以下给出的答案确实有效:将起始值从scala> def func(map: collection.Map[Int, Int]): collection.Map[Int, Int] = map func: (map: scala.collection.Map[Int,Int])scala.collection.Map[Int,Int] scala> Seq(1, 2, 3).foldLeft(collection.Map.empty[Int, Int])((map, i) => map + (i -> i)) res11: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3) scala> Seq(1, 2, 3).foldLeft(collection.Map.empty[Int, Int])((map, i) => func(map) + (i -> i)) <console>:9: error: type mismatch; found : scala.collection.Map[Int,Int] required: scala.collection.immutable.Map[Int,Int] Seq(1, 2, 3).foldLeft(collection.Map.empty[Int, Int])((map, i) => func(map) + (i -> i)) ^ 更改为collection.Map.empty[Int, Int]。我不确定为什么这会有所不同:

collection.Map[Int, Int]()

2 个答案:

答案 0 :(得分:3)

您不必投出它,因为您已经定义了类型:

Seq(1, 2, 3).foldLeft(collection.Map[Int, Int]()) {
  case (map, i) => map + (i -> i)
}

答案 1 :(得分:1)

  

修改

方法empty返回:

def empty[A, B]: immutable.Map[A, B] = immutable.Map.empty

这就是为什么你有错误类型,因此,创建一个()的对象,会返回正确的类型,collection.Map[Int, Int]

def func(map: collection.Map[Int, Int]): collection.Map[Int, Int] = map

Seq(1, 2, 3).foldLeft(collection.Map[Int, Int]())((res, i) =>
  res + (i -> i)
) 
  

地图(1 - > 1,2 - > 2,3 - > 3)