modeling out of memory

Duncan Coutts
Sun, 2 Mar 2003 23:54:24 +0000

On Sun, 2 Mar 2003 10:16:12 +0200
"Cagdas Ozgenc" <> 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 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:

BTW HeapOverflow doesn't actually work yet according to the ghc