繁体   English   中英

如何定义类型:无限功能?

[英]How to define a type: infinite function?

如何定义一个类型InfiniteFunction ,它是一个函数,并在被调用时返回另一个InfiniteFunction

类型如下:

() => () => () => ... // infinite

或递归:

type InfiniteFunction = () => InfiniteFunction

这不起作用

scala> type InfiniteFunction = () => InfiniteFunction
<console>:11: error: illegal cyclic reference involving type InfiniteFunction
       type InfiniteFunction = () => InfiniteFunction

问题

我想对这个函数进行cps转换:

def travel(tree: TreeNode): Unit = {
  if (tree != null) {
    travel(tree.left)
    println(tree.value)
    travel(tree.right)
  }
}

在cps之后:

def r[T](f: => T): () => T = () => f
def travel(tree: TreeNode, cb: () => AnyRef): Unit = {
  if (tree != null) {
    travel(tree.left, r{
      println(tree.value)
      travel(tree.right, cb)
    })
  } else {
    cb()
  }
}

然后我想通过产生它们来优化尾调用,而不是调用它们:

def r[T](f: => T): () => T = () => f
def travel(tree: TreeNode, cb: () => InfiniteFunction): InfiniteFunction = {
  if (tree != null) {
    r(travel(tree.left, r{
      println(tree.value)
      r(travel(tree.right, cb))
    }))
  } else {
    r(cb())
  }
}

// demonstration how to use travel
var f: InfiniteFunction = r(
  travel(tree, r(throw new RuntimeException("it is over")))
)
// this will end by the exception "it is over"
while (true) f = f()

这里所述类型InfiniteFunction是需要的,W / O型的InfiniteFunction类型,需要类型转换:

def r[T](f: => T): () => T = () => f
def travel(tree: TreeNode, cb: () => AnyRef): () => AnyRef = {
  if (tree != null) {
    r(travel(tree.left, r {
      println(tree.value)
      r(travel(tree.right, cb))
    }))
  } else {
    r(cb())
  }
}

var f: () => AnyRef = r(
  travel(tree, r(throw new RuntimeException("it is over")))
)
while (true) f = f().asInstanceOf[() => AnyRef]

使用特征而不是类型别名来解决循环引用的问题:

trait Inf extends (Unit => Inf)

Unit也是()的类型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM