Skip to content

How to traverse an array of IDisposable? Array as Traversable and IDisposable as Applicative bracket? #1310

Answered by louthy
ingun37 asked this question in Q&A
Discussion options

You must be logged in to vote

For the exact example with the IO monad:

public static IO<C> bracket<A, B, C>(
    IO<A> acquire,
    Func<A, IO<B>> release,
    Func<A, IO<C>> action) =>
    IO.lift(env =>
    {
        var x = acquire.Run(env);
        try
        {
            return action(x).Run(env);
        }
        finally
        {
            release(x).Run(env);
        }
    });

If the acquired resource is IDisposable then you can write a bracket function that doesn't need a release lambda argument:

public static IO<B> bracket<A, B>(
    IO<A> acquire,
    Func<A, IO<B>> action)
    where A : IDisposable =>
    IO.lift(env =>
    {
        var x = acquire.Run(env);
        try
        {
            return a…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by ingun37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants