17

Do you know if are there pointers in Haskell?

  • If yes: how do you use them? Are there any problems with them? And why aren't they popular?

  • If no: is there any reason for it?

1

3 Answers 3

25

Yes there are. Take a look at Foreign.Ptr or Data.IORef

I suspect this wasn't what you are asking for though. As Haskell is for the most part without state, it means pointers don't fit into the language design. Having a pointer to memory outside the function would mean that a function is no longer pure and only allowing pointers to values within the current function is useless.

2
  • 22
    I suspect that he's looking for a way to pass around large data structures without creating copies, based on the wrong assumption that passing a value to a function creates a copy like it does when doing call-by-value in C++.
    – sepp2k
    Mar 14, 2010 at 19:21
  • 1
    @sepp2k or for talking to memory mapped devices.
    – user142019
    Dec 16, 2011 at 14:52
14

Haskell does provide pointers, via the foreign function interface extension. Look at, for example, Foreign.Storable.

Pointers are used for interoperating with C code. Not for every day Haskell programming.

If you're looking for references -- pointers to objects you wish to mutate -- there are STRef and IORef, which serve many of the same uses as pointers. However, you should rarely -- if ever -- need Refs.

0
10

If you simply wish to avoid copying large values, as sepp2k supposes, then you need do nothing: in most implementation, all non-trivial values are allocated separately on a heap and refer to one another by machine-level addresses (i.e. pointers). But again, you need do nothing about any of this, it is taken care of for you.

To answer your question about how values are passed, they are passed in whatever way the implementation sees fit: since you can't mutate the values anyway, it doesn't impact the meaning of the code (as long as the strictness is respected); usually this works out to by-need unless you're passing in e.g. Int values that the compiler can see have already been evaluated...

Pass-by-need is like pass-by-reference, except that any given reference could refer either to an actual evaluated value (which cannot be changed), or to a "thunk" for a not-yet-evaluated value. Wikipedia has more.

1
  • 1
    This is one of the major strong points of Haskell: you have to do very little to ensure efficiency in most cases.
    – avpx
    Mar 30, 2010 at 0:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.