Re: global variable

Glynn Clements <[email protected]>
Newsgroups gmane.comp.lang.haskell.hugs.user
Message-ID <[email protected]>
Jose Morais wrote:

> 	I need a function called, say, newItem :: Int, that when first called
> returns 1, the next time it is called it would return 2, then 3 and so
> on.

That isn't a function. A function is a mapping from argument values to
result values; the result depends solely upon the argument.

Unlike many other languages, Haskell's "functions" really are
functions, not value-returning procedures (which is what most other
languages seem to mean by "function").

> How can I achieve this?

You can't. At least, not without using unsafePerformIO, which:

a) isn't in the Haskell 98 standard, and

b) is more likely to result in confusion than in working code (some
uses of unsafePerformIO are easy to get right; this isn't one of
them).

A more realistic approach is to use a monad which supports mutable
references, e.g. the ST monad with STRefs or the IO monad with IORefs.
See:

	http://www.haskell.org/ghc/docs/latest/html/base/Data.STRef.html
	http://www.haskell.org/ghc/docs/latest/html/base/Data.IORef.html

BTW, you will probably need to be familiar with state monads (e.g. 
Haskell I/O) in order to make any sense of that.

-- 
Glynn Clements <[email protected]>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.