Result type
Last updated
Was this helpful?
Last updated
Was this helpful?
A.k.a Either
(Haskell)
Models a double-track Success/Failure
Functional way of dealing with business errors (expected errors)
Allows exceptions to be used only for exceptional errors
As soon as an operation fails, the remaining operations are not launched
đ
Main functions:
map f result
: to map the success
⢠('T -> 'U) -> Result<'T, 'Error> -> Result<'U, 'Error>
mapError f result
: to map the error
⢠('Err1 -> 'Err2) -> Result<'T, 'Err1> -> Result<'T, 'Err2>
bind f result
: same as map
with f
returning a Result
⢠('T -> Result<'U, 'Error>) -> Result<'T, 'Error> -> Result<'U, 'Error>
⢠đĄ The result is flattened, like the flatMap
function on JS arrays
⢠â ď¸ Same type of 'Error
for f
and the input result
.
đĄ Since F⯠7.0, more functions have been added to the Result
module, but some functions are missing compared to the Option
module:
Ok value
Some value
[ value ]
Error err
None
[ ]
Result.isOk
/ Result.isError
Option.isSome
/ Option.isNone
Ă / List.isEmpty
Result.contains okValue
Option.contains someValue
List.contains value
Result.count
Option.count
List.length
â (O(N))
Result.defaultValue value
Option.defaultValue value
Ă
Result.defaultWith defThunk
Option.defaultWith defThunk
Ă
Ă
Option.filter predicate
List.filter predicate
Result.iter action
Option.iter action
List.iter action
Result.map f
Option.map f
List.map f
Result.mapError f
Ă
Ă
Result.bind f
Option.bind f
List.bind f
Result.fold f state
Option.fold f state
List.fold f state
Result.toArray
/ toList
Option.toArray
/ toList
Ă
Result.toOption
Ă
Ă
Implement Result.map
and Result.bind
đĄ Tips:
Map the Success track
Access the Success value using pattern matching
map
: no track change
bind
: eventual routing to Failure track, but never vice versa
â The mapping/binding operation is never executed in track Failure.
Result
vs Option
Option
can represent the result of an operation that may fail
â But if it fails, the option doesn't contain the error, just None
Option<'T>
â Result<'T, unit>
â Some x
â Ok x
â None
â Error ()
â See Result.toOption
(built-in) and Result.ofOption
(below)
The Option
type is part of F# from the get go
The Result
type is more recent: introduced in F# 4.1 (2016)
The Option
type (alias: option
) is a regular union: a reference type
The Result
type is a struct union: a value type
The ValueOption
type (alias: voption
) is a struct union: ValueNone | ValueSome of 't
Let's change our previous checkAnswer
to indicate the Error
: