在Scala的溪流

Scala | 流 (Scala | Streams)

Stream in Scala is a type of lazy val. It is a lazy val whose elements are evaluated only when they are used in the program. Lazy initialization is a feature of Scala that increases the performance of the program.

Scala中的Stream是一种惰性val 。 这是一个懒惰的val,其元素仅在程序中使用时才被评估。 延迟初始化是Scala的一项功能,可以提高程序的性能。

Syntax:

句法:

    val str = 1 #:: 2 #:: 3 #:: Stream.empty

Elements of a stream are created using #:: operator using Stream.empty at the end of initialization.

在初始化结束时,使用#::运算符使用Stream.empty创建流的元素。

Program to show the creation of a stream

显示流创建的程序

object myObject 
{ 
	def main(args:Array[String]) 
	{ 
		val myStream =  2 #:: 4 #:: 6 #:: Stream.empty; 
		println("New Stream created...")
		println(myStream)
	} 
}

Output

输出量

New Stream created...
Stream(2, <not computed>)

Creating stream using stream.cons

使用stream.cons创建流

You can create a stream using stream.cons. It will create an immutable stream and needs an import statement Scala.collection.immutable.Stream.cons.

您可以使用stream.cons创建流。 它将创建一个不可变的流,并且需要一个导入语句Scala.collection.immutable.Stream.cons 。

import scala.collection.immutable.Stream.cons 

object myObject 
{ 
	def main(args:Array[String]) 
	{ 
		val myStream: Stream[Int] = cons(2, cons(4, cons(6, Stream.empty)))
		println("New Stream created...")
		println(myStream)
	} 
}

Output

输出量

New Stream created...
Stream(2, <not computed>)

Accessing elements of the stream

访问流中的元素

In streams, take method is used to take/access elements.

在流中, take方法用于获取/访问元素。

Program to access elements using take method

程序使用take方法访问元素

import scala.collection.immutable.Stream.cons

object myObject 
{ 
	def main(args:Array[String]) 
	{ 
	    val myStream: Stream[Int] = cons(2, cons(4, cons(6, cons(9, Stream.empty))))
		print("Accessing Stream : ")
		print(myStream) 
		print("\nTake first 2 elements of stream : ") 
		myStream.take(2).print
		print("\nTake all elements from stream : ") 
		myStream.take(5).print
	} 
} 

Output

输出量

Accessing Stream : Stream(2, <not computed>)
Take first 2 elements of stream : 2, 4
Take all elements from stream : 2, 4, 6, 9

Creating an empty Stream

创建一个空流

You can create an empty stream in Scala using Stream.empty.

您可以使用Stream.empty在Scala中创建一个空流。

object myObject 
{ 
    def main(args:Array[String]) 
    { 
        val myStream: Stream[Int] = Stream.empty[Int] 
        print("This is an empty Stream : ") 
        println(myStream)
    } 
} 

Output

输出量

This is an empty Stream : Stream()


翻译自: https://www.includehelp.com/scala/streams.aspx

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值