简体   繁体   English

为什么`take`返回大数[],即使列表是无限的?

[英]Why does `take` with a large number return [] even though the list is infinite?

I have a doubt on why Haskell couldn't handle the following line 我怀疑为什么Haskell无法处理以下行

Prelude> take 1000000000000 $ repeat ' '

That line of code will return: 该行代码将返回:

""

Which is obviously not 1,000,000,000,000 spaces. 这显然不是1,000,000,000,000个空间。

If I try one less zero, it will print a long time. 如果我尝试少于零,它会打印很长时间。

And the thing that bothers me the most is that if I just write 最困扰我的是,如果我只是写作

Prelude> repeat ' '

It will work, even being a lot of more zeros. 它将工作,甚至是更大量的零。

So, why couldn't Haskell just print for a long time like it did with the repeat alone? 那么,为什么Haskell不能像单独repeat一样打印很长时间?

Are you on a 32 bit system? 你是32位系统吗? I suspect 1000000000000 wraps Int into a negative number. 我怀疑1000000000000将Int包装成负数。 It's equal to about 2^40 . 它等于大约2^40

You can check what's going on by entering 1000000000000 :: Int . 您可以通过输入1000000000000 :: Int来查看正在进行的操作。

take with a negative number just returns the empty list: take负数只需返回空列表:

Prelude> take (- 1) [1,2,3]
[]

For reference, take only takes Int : 作为参考, take只需要Int

Prelude> :t take
take :: Int -> [a] -> [a]

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

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