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]
sos2。运行
具有类型RNG=>(Int,RNG)
。