Optional represents a value that may be missing and Result an operation that may go well or badly; both force you to look at the bad case before using the value.
Optional<T> has two shapes: Some(value) when there is a value and None when it is missing.
Result<T,E> has two shapes: Success(value) when the operation went well and Failure(error) when it did not.
Like any variant, they are queried with Switch. There is no way to "take the value out and hope it is there": the program has to decide what to do in both cases.
ProgramA division that may fail
Subroutinedividir(aAsInteger,bAsInteger)AsResult<Integer,String>Ifb=0ThenReturnFailure("no se divide entre cero");EndIfReturnSuccess(aDivb);EndSubroutineAlgorithmDivisionSwitchdividir(10,2)DoSuccess(cociente):Write"Cociente: ",cociente;Failure(motivo):Write"Error: ",motivo;EndSwitchSwitchdividir(1,0)DoSuccess(cociente):Write"Cociente: ",cociente;Failure(motivo):Write"Error: ",motivo;EndSwitchEndAlgorithm
Output
Cociente: 5
Error: no se divide entre cero
The program finishes normally.
Figure 3.10-1.Two boxes that may or may not be full. To open them, both possibilities must be considered.
Two columns. Optional can be Some with a value or None. Result can be Success with a value or Failure with a reason. Below, a note says both cases must be considered with Switch, and that Propagate passes the error upwards.
3.10.3 Propagate
Inside a subroutine that also returns Result (or Optional), Propagate avoids writing a Switch for every call: if the value is Success, it gives its content; if it is Failure, it ends the subroutine returning that same error.
ProgramPassing the error upwards
Subroutinedividir(aAsInteger,bAsInteger)AsResult<Integer,String>Ifb=0ThenReturnFailure("no se divide entre cero");EndIfReturnSuccess(aDivb);EndSubroutineSubroutinemitadDelCociente(aAsInteger,bAsInteger)AsResult<Integer,String>DefinecAsInteger<-Propagatedividir(a,b);ReturnSuccess(cDiv2);EndSubroutineAlgorithmEncadenarSwitchmitadDelCociente(20,0)DoSuccess(valor):Writevalor;Failure(motivo):Write"Falló: ",motivo;EndSwitchEndAlgorithm
Output
Falló: no se divide entre cero
The program finishes normally.
Discard makes it clear that you ignore a Result on purpose: Discarddividir(4,2);.
In short
Optional<T>: Some(value) or None.
Result<T,E>: Success(value) or Failure(error).
They are queried with Switch; there is no shortcut that ignores the bad case.
Propagate returns the error upwards; Discard ignores it on purpose.