简体   繁体   English

Haskell无限循环,简单地重新放行动

[英]Haskell infinite loop with simply re-let action

I have such code: 我有这样的代码:

Prelude> let n = [1,2,3,4]
Prelude> n
[1,2,3,4]
Prelude> 0:n
[0,1,2,3,4]
Prelude> let n = 0:n

And when I type in Haskell interpreter after upper: 当我在上面输入Haskell解释器后:

Prelude> n

I'm getting the infinite result: 我得到了无限的结果:

[0,0,0,0,0,0,0,0,0

And where printing " 0, " is infinite. 打印“0”的地方是无限的。

Why do I get such result? 为什么我会得到这样的结果?
Is there some recursive stuff, and why/how does it work in interpreater level? 是否有一些递归的东西,为什么/它如何在解释器级别工作?
Could I catch stack overflow, which such stuff on GHCi or not? 我可以抓住堆栈溢出,GHCi上的这些东西是不是?

Thanks, 谢谢,
Best Regards! 最好的祝福!

The new binding of n shadows the old one. n的新绑定会影响旧的绑定。 You don't reassign to variables in Haskell. 您不会重新分配Haskell中的变量。

What Josh is saying is that you definition of n expands as: 乔什所说的是你对n的定义扩展为:

0:n.  -- note n still equals 0:n, just like you said
0:0:n. -- note n _still_ equals 0:n
0:0:0:n
...

Haskell's let is like letrec in other languages such as ML: bindings are allowed to be recursive. Haskell的let就像其他语言中的letrec ,例如ML:允许绑定是递归的。 In other words n = 0:n defines n to be a list where the first element is 0 and the rest of the list is equal to n . 换句话说n = 0:n定义n是一个列表,其中所述第一元件是0和列表的其余部分是等于n That means that the second element of n is equal to the first element of n , which is 0 , etc. 这意味着,第二元件n等于第一元件n ,这是0 ,等等。

Infinite lists are OK in Haskell due to laziness. 由于懒惰,无限列表在Haskell中是可以的。 If you only ever use the first 10 elements of the list, then the 11th element and beyond will never be evaluated. 如果您只使用列表的前10个元素,那么将永远不会评估第11个元素和更高元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM