[Haskell-cafe] the Haskell "with" "pattern"?

Luke Palmer lrpalmer at gmail.com
Wed Aug 6 06:03:16 EDT 2008


2008/8/6 Galchin, Vasili <vigalchin at gmail.com>

> Hi Jeremy and the haskell community,
>
>     I think now my question is why isn't there a higher-order "with"
> function in the Haskell Prelude?
>

There is.  Well, not in the prelude, but in the base package at least.  It's
called "bracket".  But I think the reason that not all "with" functions are
implemented with bracket is because "with" is not as well defined as a
function; it is an idiom, and varies in too many ways to have a well-defined
semantics.

However, you could presumably abstract this more using typeclasses with
fundeps or associated types.

class Resource a where
    type Constr a
    acquire :: Constr a -> IO a
    release :: a -> IO ()

with :: (Resource a) => Constr a -> (a -> IO b) -> IO b
with constr = bracket (acquire constr) release

I haven't calculated how many of the existing with* functions would fit into
this abstraction.

Luke


> Regards, Vasili
>
> On Wed, Aug 6, 2008 at 2:25 AM, Jeremy Shaw <jeremy at n-heptane.com> wrote:
>
>> At Wed, 6 Aug 2008 00:43:55 -0500,
>> Galchin, Vasili wrote:
>> >
>> > [1  <multipart/alternative (7bit)>]
>> > [1.1  <text/plain; ISO-8859-1 (7bit)>]
>> > Hello,
>> >
>> >     1) Is there a common assumed semantics across all of the Haskell
>> "with"
>> > things? withString? withData?
>>
>> A vague semantic is that some resource is acquired, used, and then
>> released.
>>
>> >     2) If the answer to 1) is yes, then does this imply some kind of
>> > polymorphism? Couldn't "with" be "reduced" to a higher order function
>> then
>> > ??
>>
>> I think Control.Exception.bracket is used to implement many, but not
>> all, of the with* functions.
>>
>> > newThing :: IO a
>> > newThing = ...
>>
>> > destroyThing :: a -> IO b
>> > destroyThing ...
>>
>> > withThing :: (Thing -> IO a) -> IO a
>> > withThing useThing = bracket newThing destroyThing useThing
>>
>> I have not fully answered either of your questions, but hopefully this
>> is a start.
>>
>> j.
>>
>
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20080806/fcd4be45/attachment.htm


More information about the Haskell-Cafe mailing list