Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.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 使用单位法_Scala_Functional Programming_Monads - Fatal编程技术网

Scala 使用单位法

Scala 使用单位法,scala,functional-programming,monads,Scala,Functional Programming,Monads,我有以下定义和实施: case class State[S, +A](run: S => (A, S)) { def map[B](f: A => B): State[S, B] = flatMap(a => unit(f(a))) def map2[B, C](sb: State[S, B])(f: (A, B) => C): State[S, C] = flatMap(a => sb.map(b => f(a, b))) d

我有以下定义和实施:

case class State[S, +A](run: S => (A, S)) {
  def map[B](f: A => B): State[S, B] =
    flatMap(a => unit(f(a)))

  def map2[B, C](sb: State[S, B])(f: (A, B) => C): State[S, C] =
    flatMap(a => sb.map(b => f(a, b)))

  def flatMap[B](f: A => State[S, B]): State[S, B] = State(s => {
    val (a, s1) = run(s)
    f(a).run(s1)
  })
}

object State {

  def unit[S, A](a: A): State[S, A] =
    State(s => (a, s))

  def get[S]: State[S, S] = State(s => (s, s))

}

trait RNG {
  def nextInt: (Int, RNG) // Should generate a random `Int`. We'll later define other functions in terms of `nextInt`.
}

object RNG {

  // NB - this was called SimpleRNG in the book text

  case class Simple(seed: Long) extends RNG {
    def nextInt: (Int, RNG) = {
      val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL // `&` is bitwise AND. We use the current seed to generate a new seed.
      val nextRNG = Simple(newSeed) // The next state, which is an `RNG` instance created from the new seed.
      val n = (newSeed >>> 16).toInt // `>>>` is right binary shift with zero fill. The value `n` is our new pseudo-random integer.
      (n, nextRNG) // The return value is a tuple containing both a pseudo-random integer and the next `RNG` state.
    }
  }
}
我的问题是,如何在
状态
对象上使用
单元
函数?我尝试了以下方法:

val s2 = State.unit[RNG, Int](4563)
println(s2.run((x: RNG) => x))
但编译器抱怨:

Error:(12, 29) type mismatch;
 found   : state.RNG => state.RNG
 required: state.RNG
    println(s2.run((x: RNG) => x)._1)

怎么了?

编译错误是由于您调用了
s2。请运行
run
是一个类型为
S=>(a,S)
的函数,因此给定state类型的值,它将返回一个包含结果和新状态的对。由于
s2
具有类型
State[RNG,Int]
s2.run
具有类型
RNG=>(Int,RNG)
,因此需要提供
RNG
的值,例如:

s2.run(new RNG.Simple(1))

您正在提供一个函数
RNG=>RNG
run
需要一个函数并返回一个元组
case类状态[S,+a](run:S=>(a,S))
,为什么我必须传递
RNG的实例。Simple
?@zero\u coding-
run
是一个从状态类型到一对
(结果类型,状态类型)的函数
因此您需要为其提供state类型的值<代码>s2
具有类型
状态[RNG,Int]
so
s2。运行
具有类型
RNG=>(Int,RNG)