FW: Haskell accumulator
jefu
jefu.jefu@verizon.net
Thu, 13 Jun 2002 18:20:27 -0700
Dominic Cooney wrote:
> foo n = do
> n' <- newIORef n
> return (\i -> do { modifyIORef n' (i+); readIORef n' })
I'm not sure such a solution should be submitted without
a MASSIVE CAVEAT - that this is not pure haskell style.
(I'm also not sure that it is really a legal answer since
I don't think it can be used anyhere in a program - but
I've not mucked around enough with IORefs to be sure.)
A state monad could also be used carrying around the
value of n and an incrementing function. And I think
thats probably closest to the kind of thing needed.
But here's another solution-that-aint, the goal is
to build a function that returns a pair containing
the incremented value and a new function (that uses
that new value) to use the next time around.
Sure, it means a bit of jiggery-pokery to work right,
we need to extract the value and the new function
separately, but why not?
data FooPair = FP Integer (Integer -> FooPair)
incg :: Integer -> Integer -> FooPair
incg n = \i -> let j = n+i in (FP j (incg j))
And for convenience :
val (FP i _) = i
fun (FP _ f) = f
It would be nicer to do this without the data declaration
defining incg :
incg n = \ i -> let j = n+i in (j,incg j)
But it makes the type checker cranky.
--
jefu -- museum of differential geometry -- mdg.org