视图和流有什么区别? [英] What is the difference between a view and a stream?

查看:56
本文介绍了视图和流有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala 2.8 集合框架中,viewtoStream 有什么区别?

In the Scala 2.8 collections framework, what is the difference between view and toStream?

推荐答案

在视图中的元素每次被访问时都会重新计算.在流中,元素在评估时被保留.

In a view elements are recomputed each time they are accessed. In a stream elements are retained as they are evaluated.

例如:

val doubled = List(1,2,3,4,5,6,7,8,9,10).view.map(_*2)
println(doubled.mkString(" "))
println(doubled.mkString(" "))

将重新评估每个元素的地图两次.第一次 println 一次,第二次一次.对比

will re-evaluate the map for each element twice. Once for the first println, and again for the second. In contrast

val doubled = List(1,2,3,4,5,6,7,8,9,10).toStream.map(_*2)
println(doubled.mkString(" "))
println(doubled.mkString(" "))

只会将元素加倍一次.

视图就像创建集合的配方.当您请求视图的元素时,它每次都会执行配方.

A view is like a recipe to create a collection. When you ask for elements of a view it carries out the recipe each time.

一个流就像一个拿着一堆干擦卡片的人.这家伙知道如何计算集合的后续元素.你可以向他索要该系列的下一个元素,并给你一张卡片,上面写着元素,还有一根绳子从卡片上系在他的手指上(帮助他记住).此外,在他给你一张卡片之前,他会解开手指上的第一根绳子并将其系在新卡片上.

A stream is like a guy with a bunch of dry-erase cards. The guy knows how to compute subsequent elements of the collection. You can ask him for the next element of the collection and gives you a card with the element written on it and a string tied from the card to his finger (to help him remember). Also, before he gives you a card he unties the first string from his finger and ties it to the new card.

如果你持有第一张卡片(即保持对流头部的引用),当你请求下一个元素时,你最终可能会用完卡片(即内存),但如果你不需要去回到第一个元素,您可以剪断绳子并将不需要的卡片交还给那个人,他可以重新使用它们(毕竟它们是干擦除的).这就是流如何在不耗尽内存的情况下表示无限序列.

If you hold onto the first card (i.e. keep a reference to the head of the stream) you might eventually run out of cards (i.e. memory) when you ask for the next element, but if you don't need to go back to the first elements you can cut the string and hand the unneeded cards back to the guy and he can re-use them (they're dry-erase afterall). This is how a stream can represent an infinite sequence without running out of memory.

这篇关于视图和流有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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