一个变量用在自己的定义中? [英] A variable used in its own definition?

查看:244
本文介绍了一个变量用在自己的定义中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无限流:

val ones:Stream [Int] = Stream.cons(1,ones)



如何在自己的声明中使用一个值?看来这应该会产生一个编译器错误,但它仍然有效。

解决方案

它并不总是一个递归定义。这实际上工作,并产生1:

  val a:Int = a + 1 
println(a)

变量 a 在您键入<$ c $时创建c> val a:Int ,所以你可以在定义中使用它。默认情况下, Int 被初始化为0。一个类将是空的。

正如@Chris指出的,Stream接受 =>流[A] 所以适用了一些其他规则,但我想解释一般情况。这个想法仍然是一样的,但变量是通过名字传递的,所以这使得计算递归。鉴于它是通过名称传递的,它会被懒惰地执行。 Stream会逐个计算每个元素,因此每次需要下一个元素时都会调用 ones ,导致再次生成相同的元素。这样做:

  val ones:Stream [Int] = Stream.cons(1,ones)
println(( (1,1,1,1,1,1,1,1)

虽然您可以使无限流更简单: Stream.continually(1) 更新由于@SethTisue在注释 Stream.continually Stream.cons 是两种完全不同的方法,结果非常不同,因为连续 => A 时,取> / code>,这意味着连续在每次元素重新计算并将其存储在内存中时, cons 可以避免将其存储n次,除非将其转换为其他结构,如 List 。只有在需要生成不同的值时,才应该使用连续。请参阅@SethTisue注释了解详细信息和示例。



但请注意,您需要指定类型,与递归函数相同。



您可以使第一个示例递归:

  lazy val b:Int = b + 1 
println(b)

这将叠加计算。

An infinite stream:

val ones: Stream[Int] = Stream.cons(1, ones)

How is it possible for a value to be used in its own declaration? It seems this should produce a compiler error, yet it works.

解决方案

It's not always a recursive definition. This actually works and produces 1:

val a : Int = a + 1
println(a)

variable a is created when you type val a: Int, so you can use it in the definition. Int is initialized to 0 by default. A class will be null.

As @Chris pointed out, Stream accepts => Stream[A] so a bit another rules are applied, but I wanted to explain general case. The idea is still the same, but the variable is passed by-name, so this makes the computation recursive. Given that it is passed by name, it is executed lazily. Stream computes each element one-by-one, so it calls ones each time it needs next element, resulting in the same element being produces once again. This works:

val ones: Stream[Int] = Stream.cons(1, ones)
println((ones take 10).toList) // List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)

Though you can make infinite stream easier: Stream.continually(1) Update As @SethTisue pointed out in the comments Stream.continually and Stream.cons are two completely different approaches, with very different results, because cons takes A when continually takes =>A, which means that continually recomputes each time the element and stores it in the memory, when cons can avoid storing it n times unless you convert it to the other structure like List. You should use continually only if you need to generate different values. See @SethTisue comment for details and examples.

But notice that you are required to specify the type, the same as with recursive functions.

And you can make the first example recursive:

lazy val b: Int = b + 1
println(b)

This will stackoverflow.

这篇关于一个变量用在自己的定义中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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