Example #1
0
        public static List <TResult> Run <TResult>(this Eff <TResult> eff)
        {
            switch (eff)
            {
            case SetException <TResult> setException:
                throw setException.Exception;

            case SetResult <TResult> setResult:
                return(new List <TResult> {
                    setResult.Result
                });

            case Delay <TResult> delay:
                return(Run(delay.Func(delay.State)));

            case Await <TResult> awaitEff:
                var handler = new NonDetHandler <TResult>(awaitEff.Continuation);
                var effect  = awaitEff.Effect;
                effect.Accept(handler);
                return(handler.Results);

            default:
                throw new NotSupportedException($"{eff.GetType().Name}");
            }
        }
Example #2
0
File: Wizard.cs Project: Dieho/Hero
 public ILive Build(string name = "Wizard", int hp = 5, int mp = 12, int damage = 24, int def = 3,
   string agression = "Wizard", int Experience = 0, int Lvl = 0, int ExperienceToLvl = 0, int X = 0, int Y = 0, int x = 0, int y = 0, Eff eff = null)
 {
     var hero = new Wizard();
     hero.SetHero(name, hp, mp, damage, def, agression, Experience, Lvl, ExperienceToLvl, X, Y, x, y,eff);
     return hero;
 }
Example #3
0
 public ILive Build(string name = "Warrior", int hp = 10, int mp = 4, int damage = 5, int def = 7,
     string agression = "Warrior", int Experience = 0, int Lvl = 0, int ExperienceToLvl = 0, int X = 0, int Y = 0, int x = 0, int y = 0, Eff eff=null, IBattleSkill bskill=null)
 {
     var hero = new Warrior();
     hero.SetHero(name, hp, mp, damage, def, agression, Experience, Lvl, ExperienceToLvl, X, Y, x, y,eff,bskill);
     return hero;
 }
Example #4
0
 public static EffEffect <TResult> AsEffect <TResult>(this Eff <TResult> eff,
                                                      [CallerMemberName] string memberName    = "",
                                                      [CallerFilePath] string sourceFilePath  = "",
                                                      [CallerLineNumber] int sourceLineNumber = 0)
 {
     return(new EffEffect <TResult>(eff, memberName, sourceFilePath, sourceLineNumber));
 }
Example #5
0
        /// <summary>
        ///   Runs the provided eff computation and returns any nondeterministic results.
        /// </summary>
        public static async Task <TResult[]> Run <TResult>(Eff <TResult> eff)
        {
            Exception?exn     = null;
            var       results = new List <TResult>();
            await eff.StartWithContinuations(async r => results.Add(r), async e => exn = e);

            return(exn == null?results.ToArray() : throw exn);
        }
Example #6
0
        public static async Task <TResult[]> Run <TResult>(Eff <TResult> eff)
        {
            var stateMachine = eff.GetStateMachine();
            var handler      = new NonDetEffectHandler <TResult>();
            await handler.Handle(stateMachine);

            return(handler.ResultHolder.GetResults());
        }
Example #7
0
        public async Task FromFunc_Typed_HappyPath()
        {
            int counter = 0;
            var eff     = Eff.FromFunc(async() => ++ counter);

            Assert.Equal(0, counter);
            Assert.Equal(1, await eff.Run(Handler));
            Assert.Equal(1, counter);
        }
Example #8
0
        public static Maybe <Unit> Run(Eff eff)
        {
            return(Run(Helper()));

            async Eff <Unit> Helper()
            {
                await eff; return(Unit.Value);
            }
        }
Example #9
0
        public static async Task <Maybe <TResult> > Run <TResult>(Eff <TResult> eff)
        {
            var stateMachine = eff.GetStateMachine();
            var handler      = new MaybeEffectHandler <TResult>();
            await handler.Handle(stateMachine);

            return(stateMachine.IsCompleted ?
                   Maybe <TResult> .Just(stateMachine.GetResult()) :
                   Maybe <TResult> .Nothing);
        }
Example #10
0
        /// <summary>
        ///   Runs the provided eff computation and returns any nondeterministic results.
        /// </summary>
        public static async Task Run(Eff eff)
        {
            Exception?exn = null;
            await eff.StartWithContinuations(async() => { }, async e => exn = e);

            if (exn != null)
            {
                throw exn;
            }
        }
Example #11
0
 public void Start <TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
 {
     this.state        = stateMachine;
     this.continuation = state =>
     {
         this.state = state;
         ((IAsyncStateMachine)state).MoveNext();
         return(this.eff);
     };
     this.eff = new Delay <TResult>(continuation, state);
 }
Example #12
0
 /// <summary>
 /// Creates a new activity if there are active listeners for it, using the specified name, activity kind, parent
 /// activity context, tags, optional activity link and optional start time.
 /// </summary>
 /// <param name="operation">The operation to whose activity will be traced</param>
 /// <param name="name">The operation name of the activity.</param>
 /// <param name="kind">The activity kind.</param>
 /// <param name="parentContext">The parent `ActivityContext` object to initialize the created activity object
 /// with</param>
 /// <param name="tags">The optional tags list to initialise the created activity object with.</param>
 /// <param name="links">The optional `ActivityLink` list to initialise the created activity object with.</param>
 /// <param name="startTime">The optional start timestamp to set on the created activity object.</param>
 /// <returns>The result of the `operation`</returns>
 public static Eff <RT, A> span <A>(
     string name,
     ActivityKind kind,
     ActivityContext parentContext,
     HashMap <string, object> tags,
     Seq <ActivityLink> links,
     DateTimeOffset startTime,
     Eff <RT, A> operation) =>
 use(default(RT).ActivitySourceEff.Map(rt => rt.StartActivity(
                                           name,
                                           kind,
                                           parentContext,
                                           tags,
                                           links,
                                           startTime)),
     act => localEff <RT, RT, A>(rt => rt.SetActivity(act), operation));
Example #13
0
        private void AwaitOnCompleted <TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine, bool safe)
            where TAwaiter : IEffect
            where TStateMachine : IAsyncStateMachine
        {
            switch (awaiter)
            {
            case IEffect effect:
                effect.SetState(state);
                this.eff = new Await <TResult>(effect, continuation, state);

                break;

            default:
                throw new EffException($"Awaiter {awaiter.GetType().Name} is not an effect. Try to use obj.AsEffect().");
            }
        }
Example #14
0
        public static async Task <TResult> Run <TResult>(this Eff <TResult> eff, IEffectHandler handler)
        {
            if (eff == null)
            {
                throw new ArgumentNullException(nameof(eff));
            }
            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }


            var result = default(TResult);
            var done   = false;

            while (!done)
            {
                switch (eff)
                {
                case SetException <TResult> setException:
                    await handler.Handle(setException);

                    break;

                case SetResult <TResult> setResult:
                    result = await handler.Handle(setResult);

                    done = true;
                    break;

                case Delay <TResult> delay:
                    eff = await handler.Handle(delay);

                    break;

                case Await <TResult> awaitEff:
                    eff = await handler.Handle(awaitEff);

                    break;

                default:
                    throw new NotSupportedException($"{eff.GetType().Name}");
                }
            }

            return(result);
        }
Example #15
0
        public static void OnAwaitedEff_Position_ShouldReturnEffAwaiter()
        {
            var stateMachine = Test().GetStateMachine();

            stateMachine.MoveNext();

            Assert.Equal(StateMachinePosition.EffAwaiter, stateMachine.Position);
            Assert.Null(stateMachine.Exception);
            Assert.IsAssignableFrom <EffStateMachine <int> >(stateMachine.EffAwaiter);
            Assert.Null(stateMachine.TaskAwaiter);
            Assert.False(stateMachine.IsCompleted);

            async Eff <int> Test()
            {
                return(await Eff.FromResult(42));
            }
        }
Example #16
0
        static T Run <T>(Eff <T> eff)
        {
            var result = default(T);
            var done   = false;

            while (!done)
            {
                switch (eff)
                {
                case SetException <T> setException:
                    throw setException.Exception;

                case SetResult <T> setResult:
                    result = setResult.Result;
                    done   = true;
                    break;

                case Delay <T> delay:
                    eff = delay.Func(delay.State);
                    break;

                case Await <T> awaitEff:
                    switch (awaitEff.Effect)
                    {
                    case ConsolePrintEffect printEffect:
                        System.Console.WriteLine(printEffect.Message);
                        break;

                    case ConsoleReadEffect readEffect:
                        string message = System.Console.ReadLine();
                        readEffect.SetResult(message);
                        break;

                    default:
                        throw new NotSupportedException($"{awaitEff.Effect.GetType().Name}");
                    }
                    eff = awaitEff.Continuation(awaitEff.State);
                    break;

                default:
                    throw new NotSupportedException($"{eff.GetType().Name}");
                }
            }

            return(result);
        }
Example #17
0
 /// <summary>
 /// Creates a new activity if there are active listeners for it, using the specified name, activity kind, parent
 /// activity context, tags, optional activity link and optional start time.
 /// </summary>
 /// <param name="operation">The operation to whose activity will be traced</param>
 /// <param name="name">The operation name of the activity.</param>
 /// <param name="kind">The activity kind.</param>
 /// <param name="tags">The optional tags list to initialise the created activity object with.</param>
 /// <param name="links">The optional `ActivityLink` list to initialise the created activity object with.</param>
 /// <param name="startTime">The optional start timestamp to set on the created activity object.</param>
 /// <returns>The result of the `operation`</returns>
 static Eff <RT, A> span <A>(
     string name,
     ActivityKind kind,
     HashMap <string, object> tags,
     Seq <ActivityLink> links,
     DateTimeOffset startTime,
     Eff <RT, A> operation) =>
 from e in runtime <RT>()
 from r in use(e.ActivitySourceEff.Map(
                   rt => e.CurrentActivity == null
                 ? rt.StartActivity(name, kind)
                 : rt.StartActivity(
                       name,
                       kind,
                       e.CurrentActivity.Context,
                       tags,
                       links,
                       startTime)),
               act => localEff <RT, RT, A>(rt => rt.SetActivity(act), operation))
 select r;
Example #18
0
        public static Maybe <TResult> Run <TResult>(Eff <TResult> eff)
        {
            switch (eff)
            {
            case ExceptionEff <TResult> setException:
                throw setException.Exception;

            case ResultEff <TResult> setResult:
                return(Maybe <TResult> .Just(setResult.Result));

            case DelayEff <TResult> delay:
                return(Run(delay.Continuation.MoveNext()));

            case AwaitEff <TResult> awaitEff:
                var handler = new MaybeEffectHandlerImpl <TResult>(awaitEff.Continuation);
                awaitEff.Awaiter.Accept(handler);
                return(handler.Result);

            default:
                throw new NotSupportedException($"{eff.GetType().Name}");
            }
        }
Example #19
0
 public static Eff <A> Repeat(Eff <A> ma, Schedule schedule) =>
 schedule.Run(ma, static x => x.IsSucc);
Example #20
0
 public static Task <List <TResult> > Run <TResult>(Eff <TResult> eff) => Run(eff.GetStateMachine());
Example #21
0
 public async Task FromFunc_Untyped_Exception()
 {
     var eff = Eff.FromFunc(async() => { throw new DivideByZeroException(); });
     await Assert.ThrowsAsync <DivideByZeroException>(() => eff.Run(Handler));
 }
Example #22
0
 public static Proxy <RT, A1, A, B1, B, R> use <RT, A1, A, B1, B, R>(Eff <R> ma)
     where RT : struct, HasCancel <RT>
     where R : IDisposable =>
 new Use <RT, A1, A, B1, B, R, R>(ma.ToAffWithRuntime <RT>, dispose, Pure <RT, A1, A, B1, B, R>);
Example #23
0
 public static Lift <RT, R> use <RT, R>(Eff <R> ma)
     where RT : struct, HasCancel <RT>
     where R : IDisposable =>
 Lift.Eff <RT, R>(ma);
    // ------------ Eff<A> ---------------------------------------------------------------------------------------------

    public static Eff <B> Apply <A, B>(this Eff <Func <A, B> > mf, Eff <A> ma) =>
    EffMaybe <B>(() =>
    {
Example #25
0
 public void SetException(Exception exception)
 {
     this.eff = new SetException <TResult>(exception, state);
 }
Example #26
0
        public static void Menu()
        {
            bool exit = false;
            string line;
            string grammar = null;
            Translate tr = new Translate();

            Console.WriteLine("Functions: ");
            Console.WriteLine("In order to set the grammar");
            Console.WriteLine("> G <rules>");
            Console.WriteLine("Ex: G S:(A,B). A:(B,'a';@). B:(C,'b';C). C:('c';@). EOGram!");
            Console.WriteLine("In order to calculate FIRST");
            Console.WriteLine("> first <k>");
            Console.WriteLine("Example: first 2");
            Console.WriteLine("In order to calcualte EFF");
            Console.WriteLine("> eff <k>");
            Console.WriteLine("Example: eff 3");
            Console.WriteLine("In order to exit the program");
            Console.WriteLine("> e - exit");
            Console.Write("> ");

            while (!exit)
            {
                line = Console.ReadLine();

                if (line.Length > 0)
                {
                    if (line.Length == 1 && line[0] == 'e')
                        exit = true;
                    else
                    {
                        List<string> parts = line.Split(' ').Where(x => x != "").ToList();
                        string fun = parts[0];

                        switch (fun)
                        {
                            case "G":
                                if (grammar == null)
                                    grammar = tr.ToMyForm(line, Translate.TYPE.GRAMMAR);
                                else
                                {
                                    Console.WriteLine("Rewrite? y/n: ");
                                    string answer = Console.ReadLine();
                                    if (answer[0] == 'y')
                                        grammar = tr.ToMyForm(line, Translate.TYPE.GRAMMAR);
                                }
                                break;
                            case "first":
                            case "eff":
                                if (grammar == null)
                                    Console.WriteLine("error: no grammar");
                                else
                                {
                                    int k;
                                    IEnumerable<string> rules = grammar.Split(' ');
                                    List<Pair<char, string>> func_rules = new List<Pair<char, string>>();

                                    if (!int.TryParse(parts[1], out k))
                                    {
                                        Console.WriteLine("error: incorrect number of k: " + parts[1]);
                                        return;
                                    }
                                    else if (k <= 0)
                                    {
                                        Console.WriteLine("error: " + k + " must be greater than 0");
                                        return;
                                    }

                                    foreach (string rule in rules)
                                    {
                                        IEnumerable<string> parts_of_rule = rule.Split('>');

                                        if (parts_of_rule.Count() != 2)
                                        {
                                            Console.WriteLine("error: " + rule + " must have two parts");
                                            return;
                                        }

                                        if (parts_of_rule.ElementAt(0).Length != 1)
                                        {
                                            Console.WriteLine("error: the left part of " + rule + " must be non-terminal");
                                            return;
                                        }

                                        char left_part = parts_of_rule.ElementAt(0)[0];

                                        foreach (string right_part in parts_of_rule.ElementAt(1).Split('|'))
                                            if (right_part == "")
                                            {
                                                Console.WriteLine("error: " + rule + " mustn\'t have the empty argument");
                                                return;
                                            }
                                            else
                                                func_rules.Add(new Pair<char, string>(left_part, right_part));
                                    }

                                    Console.WriteLine("Ex: S");
                                    Console.WriteLine("Input sequence: ");
                                    Console.Write("> ");
                                    string sequence = tr.ToMyForm(Console.ReadLine(), Translate.TYPE.SEQUENCE);

                                    if (fun == "first")
                                    {
                                        First first = new First(k, Auxiliary.StrK('A', tr.Table.Count), tr.Terms.ToString(), func_rules);
                                        Console.WriteLine(first.Execute(sequence).ToString());
                                        break;
                                    }
                                    else
                                    {
                                        Eff eff = new Eff(k, Auxiliary.StrK('A', tr.Table.Count), tr.Terms.ToString(), func_rules);
                                        Console.WriteLine(eff.Execute(sequence).ToString());
                                        break;
                                    }
                                }
                                break;
                        }
                    }
                }
                else
                    Console.WriteLine("Try again\n");
                Console.Write("> ");
            }
        }
Example #27
0
 public static Lift <RT, R> lift <RT, R>(Eff <R> ma) where RT : struct, HasCancel <RT> =>
 Lift.Eff <RT, R>(ma);
Example #28
0
 public static Proxy <RT, A1, A, B1, B, R> use <RT, A1, A, B1, B, R>(Eff <R> ma, Func <R, Unit> dispose)
     where RT : struct, HasCancel <RT> =>
 new Use <RT, A1, A, B1, B, R, R>(ma.ToAffWithRuntime <RT>, dispose, Pure <RT, A1, A, B1, B, R>);
Example #29
0
 public static Proxy <RT, A1, A, B1, B, R> lift <RT, A1, A, B1, B, R>(Eff <RT, R> ma) where RT : struct, HasCancel <RT> =>
 Disposable <R> .IsDisposable
         ? use <RT, A1, A, B1, B, R>(ma, anyDispose)
 : new M <RT, A1, A, B1, B, R>(ma.Map(Pure <RT, A1, A, B1, B, R>).ToAff());
Example #30
0
        public async Task FromResult_ShouldReturnResult()
        {
            var eff = Eff.FromResult(42);

            Assert.Equal(42, await eff.Run(Handler));
        }
Example #31
0
 public static Proxy <RT, A1, A, B1, B, R> use <RT, A1, A, B1, B, R>(Eff <RT, R> ma)
     where RT : struct, HasCancel <RT>
     where R : IDisposable =>
 new Use <RT, A1, A, B1, B, R, R>(() => ma, dispose, Pure <RT, A1, A, B1, B, R>);
Example #32
0
File: Hero.cs Project: Dieho/Hero
 //#region DDBuild
 protected Hero SetHero(string name, int hp, int mp, int damage, int def, string agression, int Experience, int Lvl, int ExperienceToLvl, int X, int Y, int x, int y, Eff effect=null, IBattleSkill bskill=null,Skill skillInUse=null)
 {
     _location.X = x;
     _location.Y = y;
     _mapPosition.X = X;
     _mapPosition.Y = Y;
     _name = name;_HP = hp;
     _HPCurent = _HP;
     _MP = mp;
     _MPCurent = _MP;
     _Damage = damage;
     _DamageCurent = _Damage;
     _Def = def;
     _DefCurent = _Def;
     _Lvl = Lvl;
     _agression = agression;
     _experience = Experience;
     _experienceToLvl = NextLvl(_Lvl);
     if (effect!=null)
     _effects.Add(effect);
     if (bskill != null)
         _battleSkills.Add(bskill);
     if (skillInUse!=null)
         _skillInUse.Add(skillInUse);
     return this;
 }
Example #33
0
 public static Proxy <RT, A1, A, B1, B, R> use <RT, A1, A, B1, B, R>(Eff <RT, R> ma, Func <R, Unit> dispose)
     where RT : struct, HasCancel <RT> =>
 new Use <RT, A1, A, B1, B, R, R>(() => ma, dispose, Pure <RT, A1, A, B1, B, R>);
Example #34
0
 public ResumableEffectHandler(Eff suspendableWorkflow)
 {
     _stateMachine = Eff.FromUntypedEff(suspendableWorkflow).GetStateMachine();
 }