global variable

Glynn Clements glynn.clements at virgin.net
Sun Oct 12 20:32:14 EDT 2003


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 <glynn.clements at virgin.net>


More information about the Hugs-Users mailing list