modeling out of memory
Duncan Coutts
duncan@coutts.uklinux.net
Sun, 2 Mar 2003 23:54:24 +0000
On Sun, 2 Mar 2003 10:16:12 +0200
"Cagdas Ozgenc" <co19@cornell.edu> wrote:
> Greetings,
>
> 1) How does one model "out of memory" condition in Haskell, perhaps using a Maybe type?
Unfortuntely not since it would not be referentially transparent. It's
part of a more general issue of exceptions in pure code.
You can't have
calculateSomething :: X -> Maybe Y
Such that it returns Nothing if it ran out of memory.
You can do it in the IO monad, which is the standard technique:
doCalculateSomething :: X -> IO (Maybe Y)
doCalculateSomething x =
catchJust asyncExceptions
(evaluate $ Just $ calculateSomething x)
handleOOM
where
handleOOM StackOverflow = return Nothing --return nothing if out of memory
handleOOM HeapOverflow = return Nothing
handleOOM otherException = ioError otherException
Probably the thing to do is just catch the exceptions rather than have
your functions return Maybe types. That way you don't have to deal with
Maybes all over the place.
See the paper on asynchronous exceptions which mentions treating out of
memory conditions as an asynchronous exception:
http://research.microsoft.com/Users/simonpj/Papers/asynch-exns.htm
BTW HeapOverflow doesn't actually work yet according to the ghc
documentation.
Duncan