16

我试图了解如何使用 scalazState执行复杂的有状态计算。这是问题所在:

给定 aList[Int]个潜在除数和 aList[Int]个数字,找到一个List[(Int, Int)] 匹配对 (divisor, number),其中一个除数最多可以匹配一个数字。

作为测试:

def findMatches(divs: List[Int], nums: List[Int]): List[(Int, Int)]

并使用以下输入:

findMatches( List(2, 3, 4), List(1, 6, 7, 8, 9) )

我们最多可以得到 3 场比赛。如果我们规定匹配必须按照它们遍历列表 lr 的顺序进行,那么匹配必须是:

List( (2, 6) ,  (3, 9) , (4, 8) )

所以需要通过以下两个测试:

assert(findMatches(List(2, 3, 4), List(1, 6, 7, 8, 9)) == List((2, 6), (3, 9), (4, 8)))
assert(findMatches(List(2, 3, 4), List(1, 6, 7, 8, 11)) == List((2, 6),  (4, 8)))

这是一个必要的解决方案:

scala> def findMatches(divs: List[Int], nums: List[Int]): List[(Int, Int)] = {
     |   var matches = List.empty[(Int, Int)]
     |   var remaining = nums
     |   divs foreach { div =>
     |     remaining find (_ % div == 0) foreach { n => 
     |       remaining = remaining filterNot (_ ==  n)
     |       matches = matches ::: List(div -> n) 
     |     }
     |   }
     |   matches
     | }
findMatches: (divs: List[Int], nums: List[Int])List[(Int, Int)]

请注意,我必须更新remaining以及 accumulating的状态matches。这听起来像是 scalaz traverse 的工作!

我无用的工作让我走到了这一步:

scala> def findMatches(divs: List[Int], nums: List[Int]): List[(Int, Int)] = {
     | divs.traverse[({type l[a] = State[List[Int], a]})#l, Int]( div =>
     | state { (rem: List[Int]) => rem.find(_ % div == 0).map(n => rem.filterNot(_ == n) -> List(div -> n)).getOrElse(rem -> List.empty[(Int, Int)]) }
     | ) ~> nums
     | }
<console>:15: error: type mismatch;
 found   : List[(Int, Int)]
 required: Int
       state { (rem: List[Int]) => rem.find(_ % div == 0).map(n => rem.filterNot(_ == n) -> List(div -> n)).getOrElse(rem -> List.empty[(Int, Int)]) }
                                                                                                                                       ^
4

2 回答 2

16

您的代码只需稍作修改即可使用 State 和 Traverse:

// using scalaz-seven
import scalaz._
import Scalaz._

def findMatches(divs: List[Int], nums: List[Int]) = {

  // the "state" we carry when traversing
  case class S(matches: List[(Int, Int)], remaining: List[Int])

  // initially there are no found pairs and a full list of nums
  val initialState = S(List[(Int, Int)](), nums)

  // a function to find a pair (div, num) given the current "state"
  // we return a state transition that modifies the state
  def find(div: Int) = modify((s: S) => 
    s.remaining.find(_ % div == 0).map { (n: Int) => 
      S(s.matches :+ div -> n, s.remaining -n)
    }.getOrElse(s))

  // the traversal, with no type annotation thanks to Scalaz7
  // Note that we use `exec` to get the final state
  // instead of `eval` that would just give us a List[Unit].
  divs.traverseS(find).exec(initialState).matches
}

// List((2,6), (3,9), (4,8))
findMatches(List(2, 3, 4), List(1, 6, 7, 8, 9))

您还可以使用runTraverseS不同的方式编写遍历:

 divs.runTraverseS(initialState)(find)._2.matches
于 2012-02-08T13:53:31.713 回答
1

经过一番折腾,我终于弄清楚了:

scala> def findMatches(divs: List[Int], nums: List[Int]): List[(Int, Int)] = {
     | (divs.traverse[({type l[a] = State[List[Int], a]})#l, Option[(Int, Int)]]( div =>
     |   state { (rem: List[Int]) => 
     |     rem.find(_ % div == 0).map(n => rem.filterNot(_ == n) -> Some(div -> n)).getOrElse(rem -> none[(Int, Int)]) 
     |   }
     | ) ! nums).flatten
     | }
findMatches: (divs: List[Int], nums: List[Int])List[(Int, Int)]

不过,我想我会查看 Eric 的答案,以更深入地了解实际发生的情况。


迭代 #2

使用 scalaz6 探索 Eric 的答案

scala> def findMatches2(divs: List[Int], nums: List[Int]): List[(Int, Int)] = {
     |   case class S(matches: List[(Int, Int)], remaining: List[Int])
     |   val initialState = S(nil[(Int, Int)], nums)
     |   def find(div: Int, s: S) = {
     |     val newState = s.remaining.find(_ % div == 0).map { (n: Int) =>
     |       S(s.matches :+ div -> n, s.remaining filterNot (_ ==  n))
     |     }.getOrElse(s)
     |     newState -> newState.matches
     |   }
     |   val findDivs = (div: Int) => state((s: S) => find(div, s))
     |   (divs.traverse[({type l[a]=State[S, a]})#l, List[(Int, Int)]](findDivs) ! initialState).join
     | }
findMatches2: (divs: List[Int], nums: List[Int])List[(Int, Int)]

scala> findMatches2(List(2, 3, 4), List(1, 6, 7, 8, 9))
res11: List[(Int, Int)] = List((2,6), (2,6), (3,9), (2,6), (3,9), (4,8))

最后joinList[List[(Int, Int)]]结局令人悲伤。相反,我们可以将最后一行替换为:

(divs.traverse[({type l[a]=State[S, a]})#l, List[(Int, Int)]](findDivs) ~> initialState).matches

迭代 #3

事实上,您可以完全取消状态计算的额外输出并进一步简化:

scala> def findMatches2(divs: List[Int], nums: List[Int]): List[(Int, Int)] = {
     | case class S(matches: List[(Int, Int)], remaining: List[Int])
     | def find(div: Int, s: S) =
     |   s.remaining.find(_ % div == 0).map( n => S(s.matches :+ div -> n, s.remaining filterNot (_ ==  n)) ).getOrElse(s) -> ()
     | (divs.traverse[({type l[a]=State[S, a]})#l, Unit](div => state((s: S) => find(div, s))) ~> S(nil[(Int, Int)], nums)).matches
     | }
findMatches2: (divs: List[Int], nums: List[Int])List[(Int, Int)]

迭代 #4

modify上面由 Apocalisp 描述的可在 scalaz6 中使用,并且无需显式提供该(S, ())对(尽管您确实需要Unitlambda 类型):

scala> def findMatches2(divs: List[Int], nums: List[Int]): List[(Int, Int)] = {
     | case class S(matches: List[(Int, Int)], remaining: List[Int])
     | def find(div: Int) = modify( (s: S) =>
     |   s.remaining.find(_ % div == 0).map( n => S(s.matches :+ div -> n, s.remaining filterNot (_ ==  n)) ).getOrElse(s))
     | (divs.traverse[({type l[a]=State[S, a]})#l, Unit](div => state(s => find(div)(s))) ~> S(nil, nums)).matches
     | }
findMatches2: (divs: List[Int], nums: List[Int])List[(Int, Int)]

scala> findMatches2(List(2, 3, 4), List(1, 6, 7, 8, 9))
res0: List[(Int, Int)] = List((2,6), (3,9), (4,8))
于 2012-02-08T13:59:01.037 回答