我正在寻找一种优雅的解决方案,用于在一系列序列中查找元素的位置。 e.g。
def findChar(c: Char, levelVector: Vector[Vector[Char]]): (x,y) = {
val x = levelVector.indexWhere(vect=>vect.indexOf(c) != -1)
(x,levelVector(x).indexOf(c))
}
这很好用,但不知怎的,我有一种直觉,应该有一个更好的优雅解决方案,一些scala或FP构造我无法回忆[多年的命令式编程可以做这种损害:)] 。 这让我做了
的工作vect.indexOf(c)
只有一次。我已经探索了其他构造,如扁平化或理解,但似乎并不优雅或简单。 我们可以假设向量是非空的,元素是唯一的。
任何赞赏的建议。
答案 0 :(得分:2)
这样的事情应该有效
def findChar(c: Char, levelVector: Vector[Vector[Char]]) = {
// view is to ensure indices are only calculated up to the element you need
val vec1 = levelVector.view.map(_.indexOf(c))
val x = vec1.indexWhere(_ != -1)
if (x != -1)
Some((x, vec1(x)))
else
None // or (-1, -1) if you prefer
}
答案 1 :(得分:0)
既不优雅也不简洁,但不过是一种解决方案,因为我强迫自己用一种理解来解决这个问题:
def findChar(c: Char, levelVector: Vector[Vector[Char]]): (Int, Int) = {
val y = for (
i <- 0 to levelVector.view.length - 1;
v = levelVector.view(i);
j = v.indexOf(c) if j != -1
) yield (i, j)
y.take(1)(0)
}
我可能很快会删除这个答案: - )