让玩具类的 Counter 如:

class Counter private( val next: Int, val str2int: Map[String,Int] ) {
  def apply( str: String ): (Int,Counter)  = str2int get str match {
    case Some(i) => ( i, this )
    case None => ( next, new Counter( next+1, str2int + (str -> next) ) )
  }
}
object Counter {
  def apply() = new Counter( 0, Map() )
}

这个类提供了一个字符串和一个自然数之间的映射,每次查询一个新的字符串时都会延迟扩展映射。

然后我可以编写一个方法,该方法可以将字符串序列转换为整数序列,在遍历过程中更新映射。我得到的第一个实现是使用 foldLeft :
def toInt( strs: Seq[String], counter: Counter ): ( Seq[Int], Counter ) =
  strs.foldLeft( (Seq[Int](), counter) ) { (result, str) =>
    val (i, nextCounter) = result._2( str )
    ( result._1 :+ i, nextCounter )
  }

这按预期工作:
val ss = Seq( "foo", "bar", "baz", "foo", "baz" )
val is = toInt( ss, Counter() )._1
            //is == List(0, 1, 2, 0, 2)

但是我对 toInt 的实现不是很满意。问题是我折叠了两个不同的值。是否有函数式编程模式来简化实现?

最佳答案

您正在寻找的模式是 State monad:

import scalaz._
import Scalaz._

case class Counter(next: Int = 0, str2int: Map[String,Int] = Map()) {
  def apply( str: String ): (Counter, Int) = (str2int get str) fold (
    (this, _),
    (new Counter(next+1, str2int + (str -> next)), next)
  )}

type CounterState[A] = State[Counter, A]

def count(s: String): CounterState[Int] = state(_(s))

def toInt(strs: Seq[String]): CounterState[Seq[Int]] =
  strs.traverse[CounterState, Int](count)

那里的类​​型注释很不幸,也许可以以某种方式消除它。无论如何,这是它的运行:
scala> val ss = Seq( "foo", "bar", "baz", "foo", "baz" )
ss: Seq[java.lang.String] = List(foo, bar, baz, foo, baz)

scala> val is = toInt(ss) ! Counter()
is: Seq[Int] = List(0, 1, 2, 0, 2)

关于design-patterns - 双折功能图案,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7177134/

10-09 02:56