Skip to content

Repository files navigation

Eff

NugetBuild & TestsLicenseGitHub language countGitHub 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:

usingNessos.Effects;asyncEffHelloWorld(){Console.WriteLine($"Hello, {awaitHelper()}!");asyncEff<string>Helper()=>"World";}

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

Effhello=HelloWorld();

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

usingNessos.Effects.Handlers;hello.Run(newDefaultEffectHandler());// "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:

publicclassCoinToss:Effect<bool>{}

Eff methods are capable of consuming abstract effects:

asyncEffTossNCoins(intn){for(inti=0;i<n;i++){boolresult=awaitnewCoinToss();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:

publicclassRandomCoinTossHandler:EffectHandler{privatereadonlyRandom_random=newRandom();publicoverrideasyncValueTaskHandle<TResult>(EffectAwaiter<TResult>awaiter){switch(awaiter){caseEffectAwaiter<bool>{Effect:CoinToss _ }awtr:awtr.SetResult(_random.NextDouble()<0.5);break;}}}

We can then execute the method by passing the handler:

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

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

publicclassBiasedCoinTossHandler:EffectHandler{privatereadonlyRandom_random=newRandom();publicoverrideasyncValueTaskHandle<TResult>(EffectAwaiter<TResult>awaiter){switch(awaiter){caseEffectAwaiter<bool>{Effect:CoinToss _ }awtr:awtr.SetResult(_random.NextDouble()<0.01);break;}}}TossNCoins(100).Run(newBiasedCoinTossHandler());// prints sequence of mostly Tails

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

About

A library design for programming with effects and handlers in C#

Resources

Stars

157 stars

Watchers

14 watching

Forks

Releases

Packages

Used by

Contributors

Languages