|
![](/i/fill.gif) |
On 11/11/2010 04:02 PM, Warp wrote:
> I know next to nothing about Haskell, but the little I have seen
> doesn't look like it would be reference-based code. It *looks* to me like
> everything is handled by value.
In normal Haskell code, all data is immutable. It's therefore impossible
to tell whether it's being passed by reference or by value; either
choice makes no difference to the end result. It only affects
performance. This is probably why Haskell "looks like" it passes by value.
> Could give a simple example which demonstrates the need for a GC?
I always used to think that creating a data structure who's size is not
statically known required handling it by reference. However, C++ somehow
manages to do this by value, so it seems my assumptions are incorrect.
In fact, thinking about it, you probably /could/ implement Haskell
without GC. It would just be far less efficient, that's all.
Anyway, as an example: Consider the function
linear a b x = a*x + b
You probably think that this function takes three numbers and returns a
number computed from them. Strictly speaking, this isn't true; in fact
this function takes three numbers and returns /an expression/ containing
them. What the caller actually gets back is a reference to the root of
an expression tree. For example, if I do "linear 2 3 5", I get back a
reference to the root of a tree that looks like
+
/ \
* 3
/ \
2 5
If I try to /use/ this value, this will execute the (+) function. The
first thing this does is inspect its arguments, which causes the (*)
function to execute. After it executes, the tree looks like
+
/ \
10 3
2 5
There are now two items of garbage: the 2 and the 5. Further, after (+)
finishes executing, we have
13
10 3
2 5
So now there's 4 items of garbage (2, 5, 10, 3).
The real situation is of course a bit more complicated than this, but
you get the idea.
Post a reply to this message
|
![](/i/fill.gif) |