[Haskell-cafe] Memoizing partially evaluated computations.

minh thu noteed at gmail.com
Wed Mar 18 07:06:26 EDT 2009


2009/3/18 Sebastiaan Visser <sfvisser at cs.uu.nl>:
> Suppose I have a list of IO computations that depends on a few very time
> consuming pure operations. The pure operations are not dependent on the real
> world:
>
>>  computation :: [IO Int]
>>  computation = [
>>      smallIOfunc timeConsumingPureOperation0
>>    , smallIOfunc timeConsumingPureOperation1
>>    , smallIOfunc timeConsumingPureOperation2
>>    , smallIOfunc timeConsumingPureOperation3
>>    ]
>>    where smallIOfunc a = print a >> return a
>
> In my main function I would like to repeatedly print the values
>
>>  main = forever $
>>    sequence_ (map (>>=print) computation)
>
> When I do this, all the time consuming operations will be reevaluated every
> run of the main loop. Is there a any (simple or smart) way to prevent the
> garbage collector from cleaning up the fully evaluated thunks inside my
> computation? As if it were something like this:
>
>>  computation :: [IO Int]
>>  computation = [smallIOfunc 42, smallIOfunc 34385, smallIOfunc 3,
>> smallIOfunc 55]
>
> Of course I could plugin some kind of Int memoizer inside my computation,
> but I do not really have the control to change things `deep' inside the
> code. I want to have some form of snapshot of a list of partially evaluated
> IO computations...
>
> Any suggestions?

Hi,

If timeConsumingPureOperation is pure, the problem is thus not related to IO,
and your question remains the same : how to memoize timeConsumingPureOperation
for some arguments. Since you want to repeatidly call main, it seems a good idea
to wrap your pure operation in a memoizing CAF (and give the wrapped version to
smalIOFuncf).

You can here : http://www.haskell.org/haskellwiki/Memoization

HTH,
Thu


More information about the Haskell-Cafe mailing list