[Haskell-cafe] A handy little consequence of the Cont monad

Henning Thielemann lemming at henning-thielemann.de
Fri Feb 1 05:12:28 EST 2008

On Fri, 1 Feb 2008, Cale Gibbard wrote:

> Hello,
> Today on #haskell, resiak was asking about a clean way to write the
> function which allocates an array of CStrings using withCString and
> withArray0 to produce a new with* style function. I came up with the
> following:
> nest :: [(r -> a) -> a] -> ([r] -> a) -> a
> nest xs = runCont (sequence (map Cont xs))
> withCStringArray0 :: [String] -> (Ptr CString -> IO a) -> IO a
> withCStringArray0 strings act = nest (map withCString strings)
>                                      (\rs -> withArray0 nullPtr rs act)
> Originally, I'd written nest without using the Cont monad, which was a
> bit of a mess by comparison, then noticed that its type was quite
> suggestive.
> Clearly, it would be more generally useful whenever you have a bunch
> of with-style functions for managing the allocation of resources, and
> would like to turn them into a single with-style function providing a
> list of the acquired resources.

Nice idea. Could serve as an explanation what the Cont monad is good for.
What about uploading it to the Wiki Category:Idioms ?

More information about the Haskell-Cafe mailing list