[Haskell-beginners] ODP: howto Pipe

Marcin Mrotek marcin.jan.mrotek at gmail.com
Thu Feb 18 17:47:49 UTC 2016


Yes, yield does return a Pipe. But "do" notation expands to a chain of
">>" and ">>=", and these functions only connect monadic values from
the same monad. Pipes are monad transformers, so the conversion from
IO to `Pipe a b IO` doesn't do anything interesting (converting back
to IO would require running the pipe, which is less trivial), but it
still has to be done for the types to agree.

Also, now I've noticed that you may have some trouble with the
`withSomething` functions. Do they take functions of type `a -> m b`
and return the result wrapped again in `m` for any monad `m`, or do
they only work with IO? If they are limited to IO, then you can't use
them here, as you would need to convert a Pipe back to IO, and this
conversion isn't a no-op and probably not what you want to do here. If
this is the case, you'd need the raw functions that open and close
these resources, and use Pipes.Safe to wrap them
(https://hackage.haskell.org/package/pipes-safe):

bracket :: MonadSafe m => Base m a -> (a -> Base m b) -> (a -> m c) -> m c

This might look a bit convoluted, but for the sake of working with
Pipes and IO, you can think of it as having type:

bracket :: IO a -> (a -> IO b) -> (a -> Pipe x y (SafeT IO) c) -> Pipe
x y (SafeT IO) c

The first argument opens some resource, the senond closes it, and the
third is the main working function. Instead of having a `Pipe x y IO
c` you have `Pipe x y (SafeT IO) c` but this is almost the same, you'd
only have to use `liftIO` instead of just `lift` to lift from IO to
this monad (or use `lift` twice, once to get `SafeT IO`, and yet again
to lift to `Pipe`), and after running the effect, use `runSafeT` to
unwrap the value to get IO (this action ensures that the finalizer you
provided to `bracket` is always executed, even if some exceptions have
been raised meanwhile).

But again, if the `withSomething` functions are polymorphic with
respect to the monad used, then you leave them as they are and don't
bother with Pipes.Safe, just wanted to warn you about a potential
problem.

Best regards,
Marcin Mrotek


More information about the Beginners mailing list