Shawn P. Garbett
listman at garbett.org
Sun Oct 12 17:32:15 EDT 2003
On Sunday 12 October 2003 2:45 pm, Jon Fairbairn wrote:
> On 2003-10-12 at 20:20BST Jose Morais wrote:
> > Hello,
> > I need a function called, say, newItem, that when
> > first called returns 1, the next time it is called it
> > would return 2, then 3 and so on. How can I achieve this?
> You can't (as Glynn has explained), and most of the time
> it's the wrong thing to do anyway. Apart from the monadic
> approach (which is perhaps a bit heavyweight), another way
> of tackling this sort of thing is to used infinite lists.
> item_numbers:: [Integer]
> item_numbers = [1..]
> You can then operate on those with map and fold.
I agree with this response. However I think a little more explaination
Think about the definition of a function. One of it's properties is that
given the same input, it generates the same output. A pure function
could not be constructed to do as the questioner ask. It would be
returning a different answer for the same inputs.
Best solution is as Jon explained. Try to find a better way to do it.
However this is not always the case. The fall back position is to create
a function that takes a seed, and this seed is preserved outside the
function in some way by the caller. Of course in this simple example,
such a seed would make the function call unnecessary and one is back to
the above simpler approach.
The next position is to use a monad. A monad allows for things like
stateful computations, in crude terms the sequence the function is
called in becomes important and is made explict and certain types of
lazy computation are no longer allowed.
Read more in : http://www.nomaware.com/monads/html/index.html and
http://www.nomaware.com/monads/html/statemonad.html Jeff Newbern's
A good example to look at related to this is the definition of Random.
More information about the Haskell-Cafe