如何映射函数';什么是Scala中的输入?
我正在尝试创建一个如何映射函数';什么是Scala中的输入?,scala,functional-programming,scala-3,Scala,Functional Programming,Scala 3,我正在尝试创建一个映射,它可以将函数的输入类型转换为另一种类型。通常当我们映射时,我们有一个函数a=>B,但由于我们映射函数中的输入,我相信这意味着我们实际上需要一个函数B=>a,如下所示: enum Result[+V, +E, +A]: case View(view: V) case Eff(eff: IO[E, Unit]) case Res(result: A, remaining: Unit => Any) object Result {
映射
,它可以将函数的输入类型转换为另一种类型。通常当我们映射时,我们有一个函数a=>B
,但由于我们映射函数中的输入,我相信这意味着我们实际上需要一个函数B=>a
,如下所示:
enum Result[+V, +E, +A]:
case View(view: V)
case Eff(eff: IO[E, Unit])
case Res(result: A, remaining: Unit => Any)
object Result {
def map[A,B,V,E](fn: A => B)(res: Result[V,E,A]): Result[V,E,B] = res match {
case View(v) => View(v)
case Eff(e) => Eff(e)
case Res(res, rem) => Res(fn(res), rem)
}
}
type ResultRun[V,E,A] = Result[V, E, A] => IO[E, Unit]
object ResultRun {
// f: A -> C
// fn: B -> A
// fn andThen f : B -> C
def map[V,E,A,B](fn: B => A)(rr: ResultRun[V,E,A]): ResultRun[V,E,B] = Result.map(fn).andThen(rr)
}
这将导致以下类型错误,这可能表明我做错了比错误所指示的更基本的事情:
[error] 50 | def map[V,E,A,B](fn: B => A)(rr: ResultRun[V,E,A]): ResultRun[V,E,B] = Result.map(fn).andThen(rr)
[error] | ^^
[error] |Found: (rr : concur.Types.ResultRun[V, E, A])
[error] |Required: concur.Types.Result[Any, Any, A] => IO[E, Unit]
[error] |
[error] |One of the following imports might make progress towards fixing the problem:
[error] |
[error] | import scalajs.js.Any.fromFunction1
[error] | import scalajs.js.ThisFunction.fromFunction1
此外,也许这应该被称为
contracmap
,而不是map
案例Eff(Eff:IO[E,Unit])
中的IO
来自哪里
如果我将IO
定义为case class IO[+X,-Y]()
,则编译以下代码:
有趣的是,我明白了-这来自ZIO库,所以我认为在我的例子中应该是
IO[+E,+A]
,因为E
或A
可能是由IO
值生成的。
enum Result[+V, +E, +A]:
case View(view: V)
case Eff(eff: IO[E, Unit])
case Res(result: A, remaining: Unit => Any)
object Result {
def map[A,B,V,E](fn: A => B)(res: Result[V,E,A]): Result[V,E,B] = res match {
case View(v) => View(v)
case Eff(e) => Eff(e)
case Res(res, rem) => Res(fn(res), rem)
}
}
type ResultRun[V,E,A] = Result[V, E, A] => IO[E, Unit]
object ResultRun {
// f: A -> C
// fn: B -> A
// fn andThen f : B -> C
def map[V,E,A,B](fn: B => A)(rr: ResultRun[V,E,A]): ResultRun[V,E,B] = Result.map[B, A, V, E](fn).andThen(rr)
}