Code Monkey home page Code Monkey logo

eff's Introduction

Eff

Nuget Build & Tests License GitHub language count GitHub top language

A library for programming with effects and handlers in C#, inspired by the Eff programming language and the implementation of Algebraic Effects in OCaml, Eff Directly in OCaml. Effects are a powerful language feature that can be used to implement dependency injection, exception handling, nondeterministic computation, trace logging and much more.

Introduction

The Eff library takes advantage of the async method extensibility features available since C# 7. At its core, the library defines a task-like type, Eff<TResult>, which can be built using async methods:

using Nessos.Effects;

async Eff HelloWorld()
{
    Console.WriteLine($"Hello, {await Helper()}!");

    async Eff<string> Helper() => "World";
}

Note that unlike Task, Eff types have cold semantics and so running

Eff hello = HelloWorld();

will have no observable side-effect in stdout. An Eff instance has to be run explicitly by passing an effect handler:

using Nessos.Effects.Handlers;

hello.Run(new DefaultEffectHandler()); // "Hello, World!"

So what is the benefit of using a convoluted version of regular async methods?

Programming with Effects

A key concept of the Eff library are abstract effects:

public class CoinToss : Effect<bool>
{
}

Eff methods are capable of consuming abstract effects:

async Eff TossNCoins(int n)
{
    for (int i = 0; i < n; i++)
    {
        bool result = await new CoinToss();
        Console.WriteLine($"Got {(result ? "Heads" : "Tails")}");
    }
}

So how do we run this method now? The answer is we need write an effect handler that interprets the abstract effect:

public class RandomCoinTossHandler : EffectHandler
{
    private readonly Random _random = new Random();

    public override async ValueTask Handle<TResult>(EffectAwaiter<TResult> awaiter)
    {
        switch (awaiter)
        {
            case EffectAwaiter<bool> { Effect: CoinToss _ } awtr:
                awtr.SetResult(_random.NextDouble() < 0.5);
                break;
        }
    }
}

We can then execute the method by passing the handler:

TossNCoins(100).Run(new RandomCoinTossHandler()); // prints random sequence of Heads and Tails

Note that we can reuse the same method using other interpretations of the effect:

public class BiasedCoinTossHandler : EffectHandler
{
    private readonly Random _random = new Random();

    public override async ValueTask Handle<TResult>(EffectAwaiter<TResult> awaiter)
    {
        switch (awaiter)
        {
            case EffectAwaiter<bool> { Effect: CoinToss _ } awtr:
                awtr.SetResult(_random.NextDouble() < 0.01);
                break;
        }
    }
}

TossNCoins(100).Run(new BiasedCoinTossHandler()); // prints sequence of mostly Tails

Please see the samples folder for more examples of Eff applications.

eff's People

Contributors

akritikos avatar dependabot[bot] avatar eiriktsarpalis avatar palladin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

eff's Issues

Better looking dependency injection?

I see next

 if (await IO<IUserService>.Do(svc => svc.CreateUser(newUserName, password)))

Anyways to improve? I think of:

  1. inject dependencies via async locals in static classes. So may be (await IO()).CreateUser` or like to look less alient?
  2. use fluent combinatorics interfaces so that delegates are Ok. Examples
        public async Task DeallocatedStop(ushort poolId, DistributedLock mutex) {
           await settings_
                .GetSettings()
                .ToAsync(poolId, GetServersForDeallocation)
                .TapAsync(mutex.Lease)
                .ToAsync(DeallocateStopServers);
        }

If I will port it to Eff tasks than Do will look in place (actually I want to call mutex.Lease and logger automatically). I have (part is here https://gist.github.com/dzmitry-lahoda/78bd89c3aa804aa0467dcba0a2e1defd#file-system-threading-tasks-funextensions-cs) combinators for Tasks, could do same for Eff and see how it looks. I was able imitate partial application with fluent combinators either.
3. Use https://github.com/dadhi/SharpIO or LanguageExt to write interpreters via LINQ DSL.

Other ideas or suggestions to try?

Question about the example EffectHandler in README.md

What is the purpose of returning the type ValueTask from Handle in the main example from README.md. Additionally this method is async but doesn't await anything awaitable, is this intentional as it seems that the async keyword could just be omitted in the example?

Recommended way for effect transformation

Hi!

I looked into the samples and have been left wondering about something. Is there a core/recommended way to facilitate mapping of one effect to another?

The idea is to be able to perform something like this:

await new CoinToss().Map(result ? "Heads" : "Tails");

Future Development and Features Roadmap

This looks really nice actually. I'm new to using Effects, but have studied it extensively in the past few months. Do you have plans to extend it further? I will be experimenting with this in a project soon, and if I'm going to extend it, I'd like to work on features that you've already thought of.

IEffect interface with default implementation (.NET standard 2.1)

I believe next is possible if to have IEffect(same as Effect) with implementation:


    public struct ConsoleReadEffect : IEffect<ConsoleReadEffect , string>
    {
    }

    public static class ConsoleEffect
    {
        public static ConsoleReadEffect Read() => default;
    }

So stateless effects can be modeled as as structs.

Null reference exception

I wanted to try your new library:
but when I copy-pasted your example https://eiriktsarpalis.wordpress.com/ into my new project (ConsoleApp):

class Program
    {
        static async Task Main(string[] args)
        {
            Eff<int> computation = SumOfSquares(1, 2, 3);
            var z = await computation.Run(new DefaultEffectHandler());
            Console.WriteLine(z);
        }

        static async Eff<int> Square(int x) => x * x;

        static async Eff<int> SumOfSquares(params int[] inputs)
        {
            var sum = 0;
            foreach (var input in inputs)
            {
                sum += await Square(input);
            }
            return sum;
        }     
    }

I got null from SumOfSquares(1, 2, 3);, so it fails on Run with NullReferenceException
I am targeting netcoreapp3.1
A version of Eff library 2.0.3

Question: Handle some effects but not all

Pardon me if this question is naive: is it possible to handle one effect and ignore another? As an example, it is quite common with exceptions to handle some exception close to the target site and let others bubble up the call stack to handle at a higher level. So it would seem similarly useful to be able to "catch", i.e. handle, some effects and let others pass through.

Pattern Matching on Eff type

Can you please provide an explanation as to how this bit of code works? It's unclear to me how the Eff gets matched to the "Set..." types like SetException.

https://github.com/nessos/Eff/blob/master/src/Eff.Core/EffExecutor.cs#L30

public static async Task<TResult> Run<TResult>(this Eff<TResult> eff, IEffectHandler handler)
        {
            ...
            var result = default(TResult);
            var done = false;
            while (!done)
            {
                switch (eff)
                {
                    case SetException<TResult> setException:
                        await handler.Handle(setException);
                        break;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.