开发者

Constructing a tuple (or list) from already-existing objects - what is the cost?

Suppose we have a function like this one:

foo (x, _, y) = (x, y)

What it does is, it takes a 3-tuple and returns a pair consisting of the first and third elements of the original tuple.

Now suppose we were to pass this function a 3-tuple consisting of some heavyweight objects. Would the two objects be copied to create a new tuple, or does the tuple's 开发者_运维知识库internal representation contain only references to objects?

I figure that, since data in Haskell is immutable, no additional copying would be needed, but I just want to be sure.

If this behavior is implementation-defined, I'd like to know what different implementations do in such cases.


It will be references - or not even that, but just a thunk. Haskell's lazy evaluation means it'll basically just remove the _ from the expression that will be expanded if you ever require its value. It's no different than basic functions like fst and snd.


x and y are pointers to the values (or, if the values haven't been evaluated yet, to the thunks). Only the pointers are copied, the values not. Basically it's implementation defined, however this is how all implementations do it as this way you can implement lazy evaluation, where the value is only evaluated at most once.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜