Scala - 减少/向左折叠
我有一个嵌套地图 m
,如下所示:
m = Map("email" -> "[电子邮件受保护]", "背景" -> 地图("语言" -> "english"))
我有一个数组 arr = Array("background","language")
如何向左折叠/减少数组并从地图中找到字符串“english” 。我尝试了这个:
arr.foldLeft(m) { (acc,x) => acc.get(x) }
但我收到此错误:
<console>:10: error: type mismatch;
found : Option[java.lang.Object]
required: scala.collection.immutable.Map[java.lang.String,java.lang.Object]
arr.foldLeft(m) { (acc,x) => acc.get(x) }
I have a nested map m
which is like:
m = Map("email" -> "[email protected]", "background" -> Map("language" -> "english"))
I have an array arr = Array("background","language")
How do I foldLeft/reduce the array and find the string "english" from the map. I tried this:
arr.foldLeft(m) { (acc,x) => acc.get(x) }
But I get this error:
<console>:10: error: type mismatch;
found : Option[java.lang.Object]
required: scala.collection.immutable.Map[java.lang.String,java.lang.Object]
arr.foldLeft(m) { (acc,x) => acc.get(x) }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(2)
十级心震2024-12-15 22:47:56
折叠作为嵌套映射的抽象并不受真正支持。另外,您处理此问题的方式将阻止类型系统为您提供太多帮助。但是,如果你坚持,那么你需要一个递归函数:
def lookup(m: Map[String,Object], a: Array[String]): Option[String] = {
if (a.length == 0) None
else m.get(a(0)).flatMap(_ match {
case mm: Map[_,_] => lookup(mm.asInstanceOf[Map[String,Object]],a.tail)
case s: String if (a.length==1) => Some(s)
case _ => None
})
}
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您应该注意类型。在这里,您从
m : Map[String, Any]
作为您的 acc 开始。您与字符串x
组合并调用get
,它返回一个Option[Object]
。要继续,您必须检查是否存在一个值,检查该值是否是 Map,强制转换(由于类型擦除而未检查,因此很危险)。我相信错误在于您的结构类型 Map[String, Any] 代表您所拥有的内容相当差。
假设你这样做
你可以添加一些帮助器来使声明树变得容易
然后声明树就像你的第一个版本一样简单,但是类型更加精确
然后你可以添加方法,例如在
trait Tree<中/code>
或者如果你想用折叠来做
You should pay attention to types. Here, you start with
m : Map[String, Any]
as your acc. You combine with a stringx
and callsget
, which returns anOption[Object]
. To continue, you must check that there is a value, check whether this value is aMap
, cast (unchecked because of type erasure, hence dangerous).I believe the fault is in the that the type of your structure, Map[String, Any] represents what you have rather poorly.
Suppose you do instead
You may add some helpers to make declaring a Tree easy
Then declaring the tree is just as easy as your first version, but the type is much more precise
You can then add methods, for instance in
trait Tree
Or if you would rather do it with a fold