[Haskell-cafe] Functions with side-effects?
David Roundy
droundy at abridgegame.org
Wed Dec 21 10:03:44 EST 2005
On Wed, Dec 21, 2005 at 11:43:42AM +0000, Daniel Carrera wrote:
> Hi all,
>
> I'm a Haskell newbie and I don't really understand how Haskell deals
> with functions that really must have side-effects. Like a rand()
> function or getLine().
>
> I know this has something to do with monads, but I don't really
> understand monads yet. Is there someone who might explain this in newbie
> terms? I don't need to understand the whole thing, I don't need a rand()
> function right this minute. I just want to understand how Haskell
> separates purely functional code from non-functional code (I understand
> that a rand() function is inevitably not functional code, right?)
What everyone said about monads is great, but I'd just like to add that for
rand() you don't strictly need a monad. With a bit of care, you could
write rand() to be of type
rand :: Int -> [Int]
where it accepts a seed value, and returns an infinite list of pseudorandom
numbers. In one sense we haven't gone non-monadic here, since there is
actually an instance of monad for [a], but you needn't actually write
monadic code.
The catch with this rand is that when you go to actually use the output,
you need to thread this list of random numbers through your code, and need
to be sure never to use the same random number twice. Which is why you'd
really prefer to use a monad that could force you to obey the constraints
of only using each random number once.
For some uses, though, the above rand will be great, as long as you're
using it for list manipulations, such as xoring a list of numbers with
random numbers as a primitive form of encryption (or a strong form of
encryption, if you use a strong random number generator).
--
David Roundy
http://www.darcs.net
More information about the Haskell-Cafe
mailing list