【问题标题】:finding a position of an element in a list of lists in functional programming在函数式编程的列表列表中查找元素的位置
【发布时间】:2014-01-01 05:39:02
【问题描述】:

我正在寻找一种优雅的解决方案来找到一个元素在序列序列中的位置。例如

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) 

只有一次。我探索了其他构造,例如扁平化或理解,但看起来并不优雅或简单。 我们可以假设向量是非空的,元素是唯一的。

任何建议表示赞赏。

【问题讨论】:

    标签: scala functional-programming


    【解决方案1】:

    这样的东西应该可以工作

    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
    }
    

    【讨论】:

    • 不知道视图是一个惰性集合。感谢您的投入。
    【解决方案2】:

    既不优雅也不简洁,但仍然是一个解决方案,我敲定了一个解决方案,因为我强迫自己使用 for 理解:

      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)
      }
    

    我可能很快就会删除这个答案:-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 2020-10-24
      • 1970-01-01
      • 2013-11-21
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      相关资源
      最近更新 更多