Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Haskell have pointers?

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?

like image 964
curioComp Avatar asked Mar 14 '10 16:03

curioComp


3 Answers

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.

like image 197
Yacoby Avatar answered Oct 24 '22 02:10

Yacoby


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.

like image 21
Don Stewart Avatar answered Oct 24 '22 02:10

Don Stewart


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.

like image 10
SamB Avatar answered Oct 24 '22 03:10

SamB