Подтвердить что ты не робот

Scala Memoization: Как работает эта записка Scala?

Следующий код из репозитория Pathikrit Dynamic Programming. Меня поражает как его красота, так и своеобразие.

def subsetSum(s: List[Int], t: Int) = {
  type DP = Memo[(List[Int], Int), (Int, Int), Seq[Seq[Int]]]
  implicit def encode(key: (List[Int], Int)) = (key._1.length, key._2)

  lazy val f: DP = Memo {
    case (Nil, 0) => Seq(Nil)
    case (Nil, _) => Nil
    case (a :: as, x) => (f(as, x - a) map {_ :+ a}) ++ f(as, x)
  }

  f(s, t)
}

Тип Memo реализуется в другом файле:

case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
  import collection.mutable.{Map => Dict}
  val cache = Dict.empty[K, O]
  override def apply(x: I) = cache getOrElseUpdate (x, f(x))
}

Мои вопросы:

  • Почему type K объявлен как (Int, Int) в subsetSum?

  • Что означает int in (Int, Int) соответственно?

3. Как (List[Int], Int) неявно конвертировать в (Int, Int)?
Я не вижу implicit def foo(x:(List[Int],Int)) = (x._1.toInt,x._2). (даже в файле Implicits.scala, который он импортирует.

* Редактировать: Ну, я пропустил это:

implicit def encode(key: (List[Int], Int)) = (key._1.length, key._2)

Мне очень нравится библиотека Pathikrit scalgos. В нем много жемчуга Scala. Пожалуйста, помогите мне в этом, чтобы я мог оценить остроумие Патикрита. Спасибо. (

4b9b3361

Ответ 1

Я являюсь автором выше кода.

/**
 * Generic way to create memoized functions (even recursive and multiple-arg ones)
 *
 * @param f the function to memoize
 * @tparam I input to f
 * @tparam K the keys we should use in cache instead of I
 * @tparam O output of f
 */
case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
  import collection.mutable.{Map => Dict}
  type Input = I
  type Key = K
  type Output = O
  val cache = Dict.empty[K, O]
  override def apply(x: I) = cache getOrElseUpdate (x, f(x))
}

object Memo {
  /**
   * Type of a simple memoized function e.g. when I = K
   */
  type ==>[I, O] = Memo[I, I, O]
}

В Memo[I <% K, K, O]:

I: input
K: key to lookup in cache
O: output

Линия I <% K означает, что K может быть видимым (т.е. неявно преобразован) из I.

В большинстве случаев I должен быть K, например. если вы пишете fibonacci, который является функцией типа Int => Int, можно кэшировать сам Int.

Но иногда, когда вы пишете memoization, вы не хотите всегда memoize или кэшировать сам вход (I), а скорее функцию ввода (K), например, когда вы пишете subsetSum, который имеет вход типа (List[Int], Int), вы не хотите использовать List[Int] как ключ в вашем кеше, но скорее хотите использовать List[Int].size как часть ключа в вашем кеше.

Итак, здесь конкретный случай:

/**
 * Subset sum algorithm - can we achieve sum t using elements from s?
 * O(s.map(abs).sum * s.length)
 *
 * @param s set of integers
 * @param t target
 * @return true iff there exists a subset of s that sums to t
 */
 def isSubsetSumAchievable(s: List[Int], t: Int): Boolean = {
    type I = (List[Int], Int)     // input type
    type K = (Int, Int)           // cache key i.e. (list.size, int)
    type O = Boolean              // output type      

    type DP = Memo[I, K, O]

    // encode the input as a key in the cache i.e. make K implicitly convertible from I
    implicit def encode(input: DP#Input): DP#Key = (input._1.length, input._2)   

    lazy val f: DP = Memo {
      case (Nil, x) => x == 0      // an empty sequence can only achieve a sum of zero
      case (a :: as, x) => f(as, x - a) || f(as, x)      // try with/without a.head
    }

    f(s, t)
 }

Вы можете, конечно, сократить все это в одну строку: type DP = Memo[(List[Int], Int), (Int, Int), Boolean]

В общем случае (при I = K) вы можете просто сделать это: type ==>[I, O] = Memo[I, I, O] и используйте его так: вычислить биномиальный коэффициент с рекурсивной memoization:

  /**
   * http://mathworld.wolfram.com/Combination.html
   * @return memoized function to calculate C(n,r)
   */
  val c: (Int, Int) ==> BigInt = Memo {
    case (_, 0) => 1
    case (n, r) if r > n/2 => c(n, n - r)
    case (n, r) => c(n - 1, r - 1) + c(n - 1, r)
  }

Подробнее о том, как работает синтаксис, пожалуйста, обратитесь к этому вопросу.

Вот полный пример, который вычисляет editDistance путем кодирования как параметров ввода (Seq, Seq), так и (Seq.length, Seq.length):

 /**
   * Calculate edit distance between 2 sequences
   * O(s1.length * s2.length)
   *
   * @return Minimum cost to convert s1 into s2 using delete, insert and replace operations
   */
  def editDistance[A](s1: Seq[A], s2: Seq[A]) = {

    type DP = Memo[(Seq[A], Seq[A]), (Int, Int), Int]
    implicit def encode(key: DP#Input): DP#Key = (key._1.length, key._2.length)

    lazy val f: DP = Memo {
      case (a, Nil) => a.length
      case (Nil, b) => b.length
      case (a :: as, b :: bs) if a == b => f(as, bs)
      case (a, b) => 1 + (f(a, b.tail) min f(a.tail, b) min f(a.tail, b.tail))
    }

    f(s1, s2)
  }

И, наконец, пример канонического фибоначчи:

lazy val fib: Int ==> BigInt = Memo {
  case 0 => 0
  case 1 => 1
  case n if n > 1 => fib(n-1) + fib(n-2)
}

println(fib(100))