在更复杂的计算中使用scalaz状态

时间:2012-02-08 13:02:50

标签: scala functional-programming scalaz

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

  

给定List[Int]个潜在除数和List[Int]个数字,找到匹配对(除数,数字)List[(Int, Int)},其中允许除数与匹配大多数号码。

作为测试:

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

并输入以下内容:

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

我们最多可以获得3场比赛。如果我们规定必须按照遍历列表l-r的顺序进行匹配,那么匹配必须

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的状态以及累积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)]) }
                                                                                                                                       ^

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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))

最后join上的List[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

上面由 Apocalisp 描述的

modify也可以在scalaz6中使用,并且无需明确提供(S, ())对(尽管您需要Unit输入lambda):

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