Confused about using Try in an enumerable
See original GitHub issueOK, bear with me with this silly example, but I’m still trying to get my head around all this stuff.
Suppose I have the following (admittedly stupid) situation: I have a Func<int, float>
that might throw an exception, for example…
Func<int, float> f = n => 1 / n;
Obviously, if you pass zero into this function it will throw an exception. Suppose I also have an Enumerable<int>
and want to apply the Func
to it…
var result = nums.Select(n => f(n));
I guess I need to use Try
to handle the fact that f
might throw an exception…
var result = nums.Select(n => Try(() => f(n));
This gives me an IEnumerable<Try<float>>
. What do I do with this now? Let’s say I have two different requirements (probably not at the same time)…
- End up with an
IEnumerable<float>
that includes only the results that didn’t throw an exception - End up with (something) that includes the exceptions. I guess this would be an
IEnumerable<Exception>
but am not sure
Anyone able to explain how I would achieve each of these goals? Thanks
Again, please forgive the silly examples, but I find playing around like this helps me understand what’s going on.
Issue Analytics
- State:
- Created 5 years ago
- Comments:5 (5 by maintainers)
Top GitHub Comments
In C# a double divided by zero is Infinity, so you wouldn’t get any exceptions, it’s nothing to do with LanguageExt’s Try.
If you go back to your original function
n => 1 / n
you should see the exceptions.You can also avoid the ToEither bit in the example as there are extensions to support IEnumerable<Try<T>> so you can simply do:
@colethecoder Thanks, that’s excellent!