Cycle around Either<> result (a SelfFoldWhile function?)
See original GitHub issueI have derived this very simple example of a problem that I’m facing:
public class CalculationTest
{
private static Either<string, decimal> Evaluate(decimal x)
{
if (x < 0 || x > 1)
return "value outside boundaries";
return x / 2;
}
[Fact]
public void Test()
{
decimal x = 0.8M;
decimal epsilon = 0.00001M;
while (x >= epsilon)
{
Either<string, decimal> v = Evaluate(x).Map(d => x = d);
if (v.IsLeft)
break;
}
Assert.True(x < epsilon);
}
}
My real code is more complex, but we can recognize the idea: I have a function that can fail (so the return type is an Either<>, with a simple string as the error, in this example), and I need to call it repeatedly progressively approximating the result (that means reusing the returned value).
This is the best formulation that I could find, but I feel there should be a more elegant solution that I don’t see…
What could be a better approach?
Thank you.
Issue Analytics
- State:
- Created 10 months ago
- Comments:7 (3 by maintainers)
Top Results From Across the Web
No results found
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

I assume
xchanges within the while loop?There’s a couple of patterns that are relevant here:
This is a recursive approach
The next way is to turn the x value into a stream of xs and
FoldorFoldWhile. You can create a stream of xs by having a for loop that yields an IEnumerable, or usePrelude.unfold:Oh, I really read it very badly… 😦 Sorry, and thanks again for your patience! Now it’s all clear! Thank you again… AB