Re:Tuples goodness in .NET 4.7.1
by SideburnsOfDoom on Monday March 12, 2018 @01:52PM
(#16569947)
Agreed. I have seen c# methods that e.g. try and parse to an int, and return int? - the Nullable generic wrapper, like a rust Option type. You use the null to mean "not parsed". That works fine for small internal methods.
Re:Tuples goodness in .NET 4.7.1
by bunderbunder on Monday March 12, 2018 @05:23PM
(#16571796)
Yeah, though, one annoyance with Nullable<T> in C# is that T must be a value type. That gets obnoxious when you want to program generically against it, because, e.g., you can't do have a method like
TValue? TryGetValue<TKey, TValue>(TKey key)
and have it work with any possible TKey. Unless they've fixed this in the past couple years, you get stuck writing your own option type to be able to also work with reference types, which is always fun to try and get past code review, or you fall back on the out parameters idiom, which is not composable.
Re:Tuples goodness in .NET 4.7.1
by SideburnsOfDoom on Tuesday March 13, 2018 @04:36AM
(#16574565)
> Yeah, though, one annoyance with Nullable<T> in C# is that T must be a value type.
Unnecessary because class types already allow null. I would not be surprised if a method e.g. public Customer TryFindCustomer(int id); returns null if it can't find the customer.
Of course, if you want to return either a customer or an error details, then you need another type or generic wrapper.
Re:Tuples goodness in .NET 4.7.1
by bunderbunder on Tuesday March 13, 2018 @09:54AM
(#16576073)
Not strictly necessary, no. But the example I wrote was getting at was meant to point out that this bifurcation can make it harder to compose generic types. It's not really an ideal design decision for modern C# so much as a hold-over from the language's early years, when idiomatic usage favored a much more imperative style of programming.
Possibly a Result in F#? Is Scala Try the equivalent of an Either monad which automatically catches underlying exceptions from Java interop?
Re:Tuples goodness in .NET 4.7.1
by bunderbunder on Monday March 12, 2018 @05:17PM
(#16571732)
To an approximation it's that. It also makes for somewhat more readable code since the properties are "result" and "error" rather than "left" and "right".
I've never liked to see much use of Either because it has the same readability issues as tuples.
It ends up being more readable. Safer, too, since, unlike for tuples, you can refuse to give up a result when the operation failed. It's also more ergonomic to use, since you can make it mappable. That way you can chain together a bunch of things that might fail, and pass along any errors, without having to stick a bunch of extra if-statements into your code.