C
C#17mo ago
LukeJ

✅ Typed delegates in maps (LanguageExt)

Hello. I'm currently doing some functional programming with the LanguageExt package. I've been going through and adding an environment to my effectful methods, which has left me with a bit of a problem. I have 3 different turn methods that I store in in map, like so
private static readonly Map<ConsoleKey, TurnMethod> TurnMethodBinding = Map(
(ConsoleKey.Z, (TurnMethod)UserTurn),
(ConsoleKey.X, AITurn),
(ConsoleKey.C, AITurnInPhases)
);
private static readonly Map<ConsoleKey, TurnMethod> TurnMethodBinding = Map(
(ConsoleKey.Z, (TurnMethod)UserTurn),
(ConsoleKey.X, AITurn),
(ConsoleKey.C, AITurnInPhases)
);
This uses the delegate TurnMethod defined as
public delegate Eff<RT, Either<TurnReturn, ExitConsole>> TurnMethod<RT>(FieldState fieldState, User player) where RT : struct, HasIO<RT>;
public delegate Eff<RT, Either<TurnReturn, ExitConsole>> TurnMethod<RT>(FieldState fieldState, User player) where RT : struct, HasIO<RT>;
As you can see though, this is typed with RT, which got added to the signature when adding an environment to the method. This causes the Map problems, saying there's an incorrect number of type paramaters. I have no idea how to do that map with the type paramater included though. Any ideas?
10 Replies
Thinker
Thinker17mo ago
Well, TurnMethod takes a single type parameter, but you're not giving it any in the map
LukeJ
LukeJ17mo ago
Right, and I have no idea how I'd add a type parameter to it. I don't know what RT is at this point in the code, so if I understand right I'd need to add typing to the map itself, which I don't know how I'd do.
Thinker
Thinker17mo ago
What is RT meant to be/do?
LukeJ
LukeJ17mo ago
It's the runtime enviroment. So anything like IO that deals with the outside world which I can either have the proper function for, or a faked version for unit tests. Following this guide on it https://github.com/louthy/language-ext/wiki/How-to-deal-with-side-effects
Thinker
Thinker17mo ago
I won't pretend I think LanuageEXT is very useful, abstracting IO like this is just unnecessary in C# imo
LukeJ
LukeJ17mo ago
Function purity is pretty fundamental in FP. Practical or not, I gotta learn it for this project.
Thinker
Thinker17mo ago
eh, arguable Anyway, you could probably specify the environment type as a type parameter on the class since that's a field
LukeJ
LukeJ17mo ago
the class? As in the one housing all these methods?
Thinker
Thinker17mo ago
ye the class containing the map
LukeJ
LukeJ17mo ago
Hmm. That would work. I think it's really starting to get hacky at that point though. Sorta how LanguageExt goes a bit but still I think I might just replace the map with a method that has a switch.