Scala,无限重复一个有限列表 [英] Scala, repeat a finite list infinitely

查看:337
本文介绍了Scala,无限重复一个有限列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在scala中使用Stream类无限重复给定列表.

I want to use Stream class in scala to repeat a given list infinitely.

例如,列表(1,2,3,4,5)我想创建一个流,该流为我提供(1,2,3,4,5,1,2,3,4,5,1, 2,3 ....)

For example the list (1,2,3,4,5) I want to create a stream that gives me (1,2,3,4,5,1,2,3,4,5,1,2,3....)

这样我可以包装Take操作.我知道这可以通过其他方式实现,但是出于某种原因,我想这样做,只是让我很幽默:)

So that I can wrap the take operation. I know this can be implemented in other ways, but I wanna do it this way for some reason, just humor me :)

所以想法是,利用从某个列表创建的这个无限循环,我可以使用take操作,并且当它到达列表的末尾时就会循环.

So the idea is that with this infinite cycle created from some list, I can use take operation, and when it reaches the end of the list it cycles.

如何制作仅重复给定列表的流?

How do I make a stream which simply repeats a given list?

推荐答案

与@Eastsun的非常相似,但更多的是揭示意图.在Scala 2.8中进行了测试.

Very similar to @Eastsun's, but a bit more intention revealing. Tested in Scala 2.8.

scala> val l  = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)

scala> Stream.continually(l.toStream).flatten.take(10).toList
res3: List[Int] = List(1, 2, 3, 1, 2, 3, 1, 2, 3, 1)

或者,使用Scalaz:

Alternatively, with Scalaz:

scala> import scalaz._
import scalaz._

scala> import Scalaz._
import Scalaz._

scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)

scala> l.toStream.repeat[Stream].join.take(10).toList
res7: List[Int] = List(1, 2, 3, 1, 2, 3, 1, 2, 3, 1)

这篇关于Scala,无限重复一个有限列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆