使用状态特征(灵感来自scalaz)制作Euler项目问题31的工作版本时遇到问题
首先,我有一个带有可变HashMap的解决方案用于记忆。它有效,但我想使用State monad,理解它并提高我的技能。
我已经将它与斐波纳契示例一起使用,但是当我尝试对我的情况应用相同的技术时,我有一个我不理解的编译器错误。
我将此实现用于State:
trait State[S, A] {
val run: S => (S, A)
def apply(s: S): (S, A) = run(s)
def eval(s: S): A = run(s)._2
def map[B](f: A => B): State[S, B] =
State { s: S =>
val (s1, a) = run(s)
(s1, f(a))
}
def flatMap[B](f: A => State[S, B]): State[S, B] =
State { s: S =>
val (s1, a) = run(s)
f(a)(s1)
}
}
object State {
def apply[S, A](f: S => (S, A)): State[S, A] = new State[S, A] {
final val run = f
}
def init[S, A](a: A) = State { s: S => (s, a) }
def update[S, A](f: S => S): State[S, Unit] = State { s: S => (f(s), ()) }
def gets[S, A](f: S => A): State[S, A] = State { s: S => (s, f(s)) }
}
我尝试使用它在这里:
val coins = List(1, 2, 5, 10, 20, 50, 100, 200)
type MemoKey = (List[Int], Int)
type MemoType = Map[MemoKey, Int]
def ways(listCoins: List[Int], amount: Int): Int = {
def ways_impl(coins: List[Int], sum: Int): State[MemoType, Int] = (coins, sum) match {
case (Nil, 0) => State.init(1)
case (Nil, _) => State.init(0)
case (c :: cs, _) =>
for {
memoed <- State.gets { m: MemoType => m.get((coins, sum)) }
res <- memoed match {
case Some(way) => State.init[MemoType, Int](way)
case None =>
(for {
i <- 0 to sum / c
r <- ways_impl(cs, sum - i * c)
_ <- State.update { m: MemoType => m + ((coins, sum) -> r) }
} yield r).sum
}
} yield res
}
ways_impl(listCoins, amount) eval (Map())
我在这一行有一个编译器错误:
r <- ways_impl(cs, sum - i * c)
编译说:
type mismatch; found : State[MemoType,Int] (which expands to) State[scala.collection.immutable.Map[(List[Int], Int),Int],Int] required: scala.collection.GenTraversableOnce[?]
有关信息,这是我的第一个带有可变地图的版本:
import scala.collection.mutable._
val memo = HashMap[(List[Int], Int), Int]()
val coins = List(1, 2, 5, 10, 20, 50, 100, 200)
def memoWays(coins: List[Int], sum: Int): Int = {
memo.getOrElse((coins, sum), {
val y = ways(coins, sum)
memo += ((coins, sum) -> y)
y
})
}
// brute force method with memoization
def ways(coins: List[Int], sum: Int): Int = (coins, sum) match {
case (Nil, 0) => 1
case (Nil, _) => 0
case (c :: cs, n) =>
(for {
i <- 0 to n / c
r = memoWays(cs, n - i * c)
} yield r).sum
}
println(s"result=${Mesure(ways(coins, 200))}")
这个错误是什么意思?为什么编译器需要GenTraversableOnce而不是State? 国家monad我不明白什么事?
而且,如果可以的话,我有一个可选的问题: 我用状态Monad回忆的方式,是一个不错的选择,或者我的第一个实现可变地图是否更好?
答案 0 :(得分:1)
问题是,您的for
理解是在尝试flatMap
两种不相关的类型:Range
和State
。你将不得不重构,虽然我不知道你怎么能以一种简单的方式利用State
。我可能会使用不可变的Map
作为备忘录,List
表示将要尝试的未来迭代,以及简单的递归迭代。