Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 如何实现返回状态的write方法_Scala - Fatal编程技术网

Scala 如何实现返回状态的write方法

Scala 如何实现返回状态的write方法,scala,Scala,我经常遇到这种类型的代码: def writeOne(s: S, a: A) : S = … def writeAll(init: S, l: List[A]) = l.foldLeft(init)(writeOne) def process = { val as : List[A] = … val init : S = new S() writeAll(init, as) } 在代码设计方面,有没有更好的方法来编写它?您愿意使用吗?state monad可以帮助您封装通过以下操作

我经常遇到这种类型的代码:

def writeOne(s: S, a: A) : S = …
def writeAll(init: S, l: List[A]) = l.foldLeft(init)(writeOne)
def process = {
  val as : List[A] = …
  val init : S = new S()
  writeAll(init, as)
}
在代码设计方面,有没有更好的方法来编写它?

您愿意使用吗?state monad可以帮助您封装通过以下操作处理状态的一些业务:

import scalaz._, Scalaz._

def writeOne(a: A): State[S, Unit] = State.modify(
  s => ??? // Do something with `s` and `a`, returning the new `S`.
)

def writeAll(l: List[A]): State[S, Unit] = l.traverseS_(writeOne)

def process = {
  val as: List[A] = ???
  val init = new S()

  writeAll(as).run(init)
}
我不觉得您的代码特别冗长或难以阅读,但如果您确实觉得自己编写的方法太多,需要一些参数
s:s
,并返回一个新的
s
,则状态单子是一种稍微清理问题的方法。

您愿意使用吗?state monad可以帮助您封装通过以下操作处理状态的一些业务:

import scalaz._, Scalaz._

def writeOne(a: A): State[S, Unit] = State.modify(
  s => ??? // Do something with `s` and `a`, returning the new `S`.
)

def writeAll(l: List[A]): State[S, Unit] = l.traverseS_(writeOne)

def process = {
  val as: List[A] = ???
  val init = new S()

  writeAll(as).run(init)
}

我不觉得您的代码特别冗长或难以阅读,但如果您确实觉得自己编写的方法太多,需要一些参数
s:s
,并返回一个新的
s
,那么状态单子是一种稍微清理问题的方法。

在哪些方面更好?可读性?性能?@LuGo我已经编辑了这个问题。在什么方面更好?可读性?性能?@LuGo我已经编辑了这个问题。我在运行时有一个编译错误:found:(S,Unit)required:SHave您为
进程
指定了返回类型吗?如果是这样,您可以使用
writeAll(as).exec(init)
仅获取最终状态值。我在运行时出现编译错误:found:(S,Unit)required:是否指定了
进程的返回类型?如果是这样,您可以使用
writeAll(as).exec(init)
仅获取最终状态值。