如何在scala中实现惰性序列(可迭代)? [英] How to implement lazy sequence (iterable) in scala?

查看:101
本文介绍了如何在scala中实现惰性序列(可迭代)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个惰性迭代器,该迭代器在3级嵌套循环中产生每个调用中的下一个元素.

I want to implement a lazy iterator that yields the next element in each call, in a 3-level nested loop.

scala中是否有与此C#代码段相似的内容:

Is there something similar in scala to this snippet of c#:

foreach (int i in ...)
    {
        foreach (int j in ...)
        {
            foreach (int k in ...)
            {
                 yield return do(i,j,k);
            }
        }
    }

谢谢杜都

推荐答案

如果将迭代器与++结合在一起,则会得到一个在两个迭代器上运行的单个迭代器. reduceLeft方法有助于将整个集合连接在一起.因此,

If you join iterators together with ++, you get a single iterator that runs over both. And the reduceLeft method helpfully joins together an entire collection. Thus,

def doIt(i: Int, j: Int, k: Int) = i+j+k
(1 to 2).map(i => {
  (1 to 2).map(j => {
    (1 to 2).iterator.map(k => doIt(i,j,k))
  }).reduceLeft(_ ++ _)
}).reduceLeft(_ ++ _)

将产生您想要的迭代器.如果您希望它比以前更懒,则还可以在前两个(1 to 2)之后添加.iterator. (当然,将每个(1 to 2)替换为您自己更有趣的集合或范围.)

will produce the iterator you want. If you want it to be even more lazy than that, you can add .iterator after the first two (1 to 2) also. (Replace each (1 to 2) with your own more interesting collection or range, of course.)

这篇关于如何在scala中实现惰性序列(可迭代)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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