What type to use to store an in-memory mutable data table in Scala?

前端 未结 5 1818
不知归路
不知归路 2020-11-28 08:55

Each time a function is called, if it\'s result for a given set of argument values is not yet memoized I\'d like to put the result into an in-memory table. One column is mea

5条回答
  •  孤城傲影
    2020-11-28 09:39

    In addition to Landei's answer, I also want to suggest the bottom-up (non-memoization) way of doing DP in Scala is possible, and the core idea is to use foldLeft(s).

    Example for computing Fibonacci numbers

      def fibo(n: Int) = (1 to n).foldLeft((0, 1)) {
        (acc, i) => (acc._2, acc._1 + acc._2)
      }._1
    

    Example for longest increasing subsequence

    def longestIncrSubseq[T](xs: List[T])(implicit ord: Ordering[T]) = {
      xs.foldLeft(List[(Int, List[T])]()) {
        (memo, x) =>
          if (memo.isEmpty) List((1, List(x)))
          else {
            val resultIfEndsAtCurr = (memo, xs).zipped map {
              (tp, y) =>
                val len = tp._1
                val seq = tp._2
                if (ord.lteq(y, x)) { // current is greater than the previous end
                  (len + 1, x :: seq) // reversely recorded to avoid O(n)
                } else {
                  (1, List(x)) // start over
                }
            }
            memo :+ resultIfEndsAtCurr.maxBy(_._1)
          }
      }.maxBy(_._1)._2.reverse
    }
    

提交回复
热议问题