Pointers and references: Difference between revisions

Content deleted Content added
m →‎{{header|Ada}}: added code highlighting
Added Haskell example
Line 216: Line 216:
cell +loop \ Advance the loop index by the size of one cell
cell +loop \ Advance the loop index by the size of one cell
;
;

=={{header|Haskell}}==

In Haskell, all normal values are immutable, and for those values pointer and reference operations make no sense. Internally, many values are ''boxed'', that is, they contain an extra indirection which can be thought of as a pointer. But that is all handled transparently by the compiler.

However, Haskell supports imperative update of variables. To ensure that these side-effects are ordered, that has to happen inside a monad. So the predefined state monad ''ST'' makes it possible to allocate a ''reference'' (a "pointer") with an initial value, read from it, and write to it:

<pre>
import Data.STRef

example :: ST s ()
example = do
p <- newSTRef 1
k <- readSTRef p
writeSTRef p (k+1)
</pre>

These are all the operations allowed on references. The type system guarantees that a reference can never leave the monad. The IO monad has similar operations ''newIORef'', ''readIORef'', ''writeIORef''. One can also embed the ST monad in the IO monad with 'stToIO'.


=={{header|Java}}==
=={{header|Java}}==