为什么Haskell的“什么都不做”函数,ID,消耗大量的内存? [英] Why does Haskell's "do nothing" function, id, consume tons of memory?

查看:202
本文介绍了为什么Haskell的“什么都不做”函数,ID,消耗大量的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Haskell有一个标识函数,它返回的输入不变。定义很简单:

  id :: a  - > a 
id x = x

所以为了好玩,这应该输出 8

  f = id id id id id id id id id id id id id id id id id id id id id id id id id id id 
main = print $ f 8



<几秒钟后(根据任务管理器约2GB内存),编译失败, ghc:内存不足。同样的,解释器说 ghci:内存不足



由于 id 是一个非常简单的函数,我不希望它在运行时或编译时成为内存负担。我们知道 id $ c>,

  id :: a  - > a 

当我们专门为 id id left left copy of id has type:

  id ::(a  - > a) - > (a  - > a)

然后当您再次为最左边的 id in id id id ,您将获得:

  id ::((a  - > a) - >(a  - > a)) - > ((a  - > a) - >(a  - > a))

查看您添加的每个 id ,最左边的 id 的类型签名是两倍大。



请注意,类型在编译期间被删除,所以这只会占用GHC中的内存。它不会占用你程序中的内存。


Haskell has an identity function which returns the input unchanged. The definition is simple:

id :: a -> a
id x = x

So for fun, this should output 8:

f = id id id id id id id id id id id id id id id id id id id id id id id id id id id
main = print $ f 8

After a few seconds (and about 2 gb of memory according to Task Manager), compilation fails with ghc: out of memory. Similarly, the interpreter says ghci: out of memory.

Since id is a pretty simple function, I wouldn't expect it to be a memory burden at run time or compile time. What is all the memory being used for?

解决方案

We know the type of id,

id :: a -> a

And when we specialize this for id id, the left copy of id has type:

id :: (a -> a) -> (a -> a)

And then when you specialize this again for the leftmost id in id id id, you get:

id :: ((a -> a) -> (a -> a)) -> ((a -> a) -> (a -> a))

So you see each id you add, the type signature of the leftmost id is twice as large.

Note that types are deleted during compilation, so this will only take up memory in GHC. It won't take up memory in your program.

这篇关于为什么Haskell的“什么都不做”函数,ID,消耗大量的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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