scala - Scala 不可变数组过滤条件
问题描述
我正在使用项目中的邻接矩阵,我需要安全地移除边缘。
我正在从事的项目以下列方式使用矩阵:
Map[Agent, Array[Edge]]
. 我想使用该Array.filter
功能来删除有问题的边缘。我这样做是为了避免使用索引或zipWithIndex
.
在向矩阵添加四个“代理”并添加两个无向边之后,这就是我的矩阵的样子:
A1: null, 1.1, null, null,
A2: 1.1, null, null, null,
A3: null, null, null, 1.2,
A4: null, null, 1.2, null,
如您所见,边缘是 (A1, A2) 和 (A3, A4)。
要删除边缘(A1,A2),我正在使用这个:
map = map.updated(a1, map(a2).filter(e => e != null && e.toAgent != a2))
但是,这将删除空条目(如预期的那样)。这是使用上述技术删除边缘后我的矩阵的样子:
A1: 1.1,
A2:
A3: null, null, null, 1.2,
A4: null, null, 1.2, null,
空条目的作用很重要,因为它允许我在正确位置快速插入新边。我正在寻找过滤掉单个边缘的解决方案。
简单地做的问题:
map = map.updated(a1, map(a2).filter(e => e.toAgent != a2))
是我正在对空条目进行操作,这会导致NullPointerException
(显然)。我正在寻找解决方案。
重申一下,我想使用每个边缘的属性进行过滤,该属性可能为空,也可能不为空。有没有办法实现一种“如果为空则跳过”?
感谢您的帮助和建议。
解决方案
你最好使用Option
而不是拥有null
元素。ScalaOption
是比null
.
A1: None, Some(1.1), None, None,
A2: Some(1.1), None, None, None,
A3: None, None, None, Some(1.2),
A4: None, None, Some(1.2), None,
你可以filter
,Option
它只会测试Some
值和跳过None
值。
map = map.updated(a1, map(a2).map(_.filter(_.toAgent == a2)))
推荐阅读
- xamarin - Xamarin,从应用内更新现有应用。没有任何服务。更新时应用未安装错误。安卓
- asp.net - Kestrel 和自签名证书。Intranet 中的桌面应用程序
- sql - 在 SQL 中的两个相同字符之间提取值
- ruby-on-rails - 退出后Rails设计登录无法正常工作
- charts - 超集周期图
- mongodb - 如何在 Mongoose 中使用过滤器获取最新记录?
- angular - 如何在提交前强制表单验证?
- spacy - spacy v3 上的 tqdm:如何批量使用它?
- android - 如何从手机存储中选择多个文件并获取全名和扩展名
- azure - 完成后如何获得 Start-AzAutomationJob 的输出?