【发布时间】:2021-05-06 23:10:32
【问题描述】:
在this session SystemFw 中给出了一个使用 vanilla scala 实现 State[S, A] 的示例,当按照示例进行操作时,我在为 vanilla State 类型提供应用程序定义时遇到了麻烦(为了获得 commands.traverse 工作.见代码here
我试图做一个隐式def来解决Applicative实例,但没有弄清楚如何处理2类型参数。
该类型如何实现Applicative:
case class State[S, A](modify: S => (A, S)) {
def runA(initial: S): A = modify(initial)._1
def flatMap[B](f: A => State[S, B]): State[S, B] =
State { s =>
val (result, nextState) = modify(s)
f(result).modify(nextState)
}
}
错误代码:
implicit def stateApplicative[S, A]: Applicative[State[S, A]] = new Applicative[State[S, A]] {
override def pure[A](x: A): State[A???] = ??? // error
override def ap[A, B](ff: State[A => B])(fa: State[A???]): State[B] = ??? // error
}
【问题讨论】:
标签: scala