[Haskell-cafe] Haskell and "memoization"

Ozgur Akgun ozgurakgun at gmail.com
Thu Dec 17 05:25:32 EST 2009


Maybe not related, but does the following prove next is called once and only
once.


import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC

next =
    do
        nextcache <- BS.readFile "next.cache"
        let nextint = readInt (BSC.unpack nextcache)
        BS.writeFile "next.cache" (BSC.pack (show (nextint+1)))
        return nextint

readInt :: String -> Int
readInt = read


I put a single character, 1 in the file "next.cache" when I run this through
ghci, and call next several times, I always get a 1. Whereas in the file
there is a 2.
I see that next is a trial of creating a function which returns different
things everytime its called, but it's in the IO monad, so that should be
doable.

When I re-run ghci, now it starts to give 2 everytime I call it. Does that
mean, it doesn't bother to re-read the file while we are in the same
process.


Hope it relates to the OP's question in some way :)

Best,

2009/12/16 Daniel Fischer <daniel.is.fischer at web.de>

> Am Mittwoch 16 Dezember 2009 15:49:54 schrieb michael rice:
> > Thanks all,
> >
> > OK, so this definition of fib
> >
> > fib 0 = 1
> > fib 1 = 1
> > fib n = fib (n-1) + fib (n-2)
> >
> > would involve a lot of recomputation for some large n,
>
> Where "large" can start as low as 20; 60 would be out of reach.
>
> > which memoization would eliminate?
>
> Right.
> >
> > Michael
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>



-- 
Ozgur Akgun
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20091217/ab5be474/attachment.html


More information about the Haskell-Cafe mailing list