Convert Result to Option
This commit is contained in:
parent
c7fabfc23b
commit
1ad83adc9d
|
@ -179,6 +179,14 @@ let x = parseInt("42").catch # equals 42.success
|
|||
let y = parseInt("XX").catch # equals int.failure(..)
|
||||
```
|
||||
|
||||
### Conversion to Option
|
||||
|
||||
Any Result can be converted to an Option:
|
||||
|
||||
```nim
|
||||
let converted = works().toOption # equals @[1, 1, 2, 2, 2].some
|
||||
```
|
||||
|
||||
Banning Errors
|
||||
--------------
|
||||
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
import ./options
|
||||
import ./resultsbase
|
||||
|
||||
include ./errorban
|
||||
|
@ -27,6 +28,12 @@ template `=?`*[T](name: untyped{nkIdent}, value: ?!T): bool =
|
|||
template name: T {.used.} = value.unsafeGet()
|
||||
value.isOk
|
||||
|
||||
proc toOption*[T,E](value: Result[T,E]): ?T =
|
||||
if value.isOk:
|
||||
value.unsafeGet.some
|
||||
else:
|
||||
T.none
|
||||
|
||||
template liftUnary(_: type Result, operator: untyped) =
|
||||
|
||||
template `operator`*(a: ?!typed): ?!typed =
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
import std/unittest
|
||||
import std/sequtils
|
||||
import std/strutils
|
||||
import pkg/questionable
|
||||
import pkg/questionable/results
|
||||
|
||||
suite "result":
|
||||
|
@ -94,6 +95,10 @@ suite "result":
|
|||
check (40.success >= 42 == false.success)
|
||||
check (40.success > 42 == false.success)
|
||||
|
||||
test "Result can be converted to Option":
|
||||
check 42.success.toOption == 42.some
|
||||
check int.failure(error).toOption == int.none
|
||||
|
||||
test "examples from readme work":
|
||||
|
||||
proc works: ?!seq[int] =
|
||||
|
|
Loading…
Reference in New Issue