C
C#2y ago
LukeJ

✅ LanguageExt bind if

I'm having trouble understanding how to do something particular in LanguageExt that I think is just a part of functional programming in general. I have an effectful method, which I then want to evaluate the result of, and rerun if not meeting a condition. Originally, I did it like this
var key = PollInput<RT>();

return key.Bind(pressedKey => pressedKey.Match(
Left: keys.Contains,
Right: _ => true)
? key
: IO<RT>.ClearCharacter()
.Bind(_ => PollValidInput<RT>(keys)));
var key = PollInput<RT>();

return key.Bind(pressedKey => pressedKey.Match(
Left: keys.Contains,
Right: _ => true)
? key
: IO<RT>.ClearCharacter()
.Bind(_ => PollValidInput<RT>(keys)));
Turns out, obviously enough, it runs PollInput twice when you do this, which isn't good. Instead, I'm now trying to do something like this
from keyPressed in PollInput<RT>()
from _ in keyPressed.Match(
Left: keys.Contains,
Right: _ => true)
? keyPressed
: IO<RT>.ClearCharacter()
.Bind(_ => PollValidInput<RT>(keys));
from keyPressed in PollInput<RT>()
from _ in keyPressed.Match(
Left: keys.Contains,
Right: _ => true)
? keyPressed
: IO<RT>.ClearCharacter()
.Bind(_ => PollValidInput<RT>(keys));
But this doesn't work, since keyPressed is not an Eff, and PollValidInput (the method this is running in), is an Eff. I have no idea how to do this. I just want to bind that else condition when that match fails, but I need to bind/map to run that condition, so I also need to return something for when that condition is met. Any ideas?
1 Reply
LukeJ
LukeJOP2y ago
Figured it out
PollInput<RT>()
.Where(keyPressed => keyPressed.Match(
Left: keys.Contains,
Right: _ => true))
.IfFailEff(IO<RT>.ClearCharacter()
.Bind(_ => PollValidInput<RT>(keys)));
PollInput<RT>()
.Where(keyPressed => keyPressed.Match(
Left: keys.Contains,
Right: _ => true))
.IfFailEff(IO<RT>.ClearCharacter()
.Bind(_ => PollValidInput<RT>(keys)));
Want results from more Discord servers?
Add your server