如何在自定义类中实现map/flatmap



我有一个名为Expect的类,在您实例化它之后,您可以构建一个数据结构(为简单起见,我们称其为树)。然后调用遍历树的run方法,在每个节点上执行一些操作。这些操作需要一些时间才能完成,因此最终结果将在将来返回。在伪代码中应该是这样的:

class Expect[R](command: String) {
  //some methods to build the tree
  def run()(implicit ec: ExecutionContext): Future[R] = {
    //Traverse the tree and execute actions on the nodes that eventually return a R
  }
}

我想用它们通常的签名实现map和flatmap,但是它们作为参数接收的函数必须在将来对返回的值进行操作。我看不出有什么办法来实现这个。

def map[T](f: R => T): Expect[T]
def flatMap[T](f: R => Expect[T]): Expect[T]

根据这些类型得出以下结论:

import scala.concurrent.{ExecutionContext, Future}
abstract class Expect[R](command: String) { self => 
  //some methods to build the tree
  def run(implicit ec: ExecutionContext): Future[R]
  def map[T](f: R => T): Expect[T] = new Expect[T](command) {
    def run(implicit ec: ExecutionContext): Future[T] =
      self.run.map(f)
  }
  def flatMap[T](f: R => Expect[T]): Expect[T] = new Expect[T](command) {
    def run(implicit ec: ExecutionContext): Future[T] =
      self.run.flatMap(r => f(r).run)
  }
}

我认为command可能不属于构造函数,它可能只是需要通过结构改进来关闭实际上使用command字符串

最新更新