sacla和python语法类似_Scala相当于Python生成器?

虽然Python生成器很酷,但是在Scala中复制它们并不是最好的方法。例如,以下代码所做的工作与您所需的相同:def classStream(clazz: Class[_]): Stream[Class[_]] = clazz match {

case null => Stream.empty

case _ => (

clazz

#:: classStream(clazz.getSuperclass)

#::: clazz.getInterfaces.toStream.flatMap(classStream)

#::: Stream.empty

)

}

在其中,流是惰性生成的,因此在请求之前它不会处理任何元素,您可以通过运行以下命令来验证:def classStream(clazz: Class[_]): Stream[Class[_]] = clazz match {

case null => Stream.empty

case _ => (

clazz

#:: { println(clazz.toString+": super"); classStream(clazz.getSuperclass) }

#::: { println(clazz.toString+": interfaces"); clazz.getInterfaces.toStream.flatMap(classStream) }

#::: Stream.empty

)

}

只要对结果Stream调用.iterator,就可以将结果转换为Iterator:def classIterator(clazz: Class[_]): Iterator[Class[_]] = classStream(clazz).iterator

使用Stream的foo定义将呈现如下:scala> def foo(i: Int): Stream[Int] = i #:: (if (i > 0) foo(i - 1) else Stream.empty)

foo: (i: Int)Stream[Int]

scala> foo(5) foreach println

5

4

3

2

1

0

另一种选择是连接不同的迭代器,注意不要预先计算它们。下面是一个示例,其中还包括帮助跟踪执行的调试消息:def yieldClass(clazz: Class[_]): Iterator[Class[_]] = clazz match {

case null => println("empty"); Iterator.empty

case _ =>

def thisIterator = { println("self of "+clazz); Iterator(clazz) }

def superIterator = { println("super of "+clazz); yieldClass(clazz.getSuperclass) }

def interfacesIterator = { println("interfaces of "+clazz); clazz.getInterfaces.iterator flatMap yieldClass }

thisIterator ++ superIterator ++ interfacesIterator

}

这很接近你的代码。与sudoYield不同,我有定义,然后我只是按照自己的意愿连接它们。

所以,虽然这不是一个答案,但我认为你找错了方向。尝试用Scala编写Python肯定是徒劳的。努力学习Scala的习惯用法,以实现同样的目标。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值