views:

310

answers:

4

hi, 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? Please help us!! :) Thank you so much!!

+10  A: 

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.

Yacoby
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
+8  A: 

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.

Don Stewart
A: 

Thank you guys for all your answers!! They were very helpfull!! - sepp2k, if haskell doesn't pass-by-value like c++, how does haskell work? is it pass-by-reference, pass-by-result or pass-by-name??? and why??

curioComp
I suggest you select one of these as the correct answer
Jonno_FTW
Generally you shouldn't answer your own question with a comment. That's what comments are for.
avpx
+1  A: 

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.

SamB
This is one of the major strong points of Haskell: you have to do very little to ensure efficiency in most cases.
avpx