I have a problem with my DU working, as expected. I defined a new DU that either has a result of type <'a>, or any exception that is thrown from System.Exception
open System // New exceptions. type MyException(msg : string) = inherit Exception(msg) type MyOtherException(msg : string) = inherit MyException(msg) // DU to store result or an exception. type TryResult<'a, 't> = | Result of 'a | Error of 't :> Exception //This is fine. let result = Result "Test" // This works, doing it in 2 steps let ex = new MyOtherException("Some Error") let result2 = Error ex // This doesn't work. Gives "Value Restriction" error. let result3 = Error (new MyOtherException("Some Error"))
I canβt understand why it allows me to create βErrorβ if I do it in 2 steps, but when I do the same in one line, I get a value limit error.
What am I missing?
thanks
UPDATE
Looking at the @kvb post, adding type information every time I needed to create an error seemed a bit verbose, so I included it in an extra method that creates an error and a bit more concise.
// New function to return a Result let asResult res : TryResult<_,Exception> = Result res // New function to return an Error let asError (err : Exception) : TryResult<unit,_> = Error(err) // This works (as before) let myResult = Result 100 // This also is fine.. let myResult2 = asResult 100 // Using 'asError' now works and doesn't require any explicit type information here. let myError = asError (new MyException("Some Error"))
I am not sure if indicating an error with "unit" will have consequences that I have not yet foreseen.
TryResult<unit,_> = Error(err)
source share