mirror of
https://github.com/logos-storage/questionable.git
synced 2026-01-07 16:23:07 +00:00
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(..)
|
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
|
Banning Errors
|
||||||
--------------
|
--------------
|
||||||
|
|
||||||
|
|||||||
@ -1,3 +1,4 @@
|
|||||||
|
import ./options
|
||||||
import ./resultsbase
|
import ./resultsbase
|
||||||
|
|
||||||
include ./errorban
|
include ./errorban
|
||||||
@ -27,6 +28,12 @@ template `=?`*[T](name: untyped{nkIdent}, value: ?!T): bool =
|
|||||||
template name: T {.used.} = value.unsafeGet()
|
template name: T {.used.} = value.unsafeGet()
|
||||||
value.isOk
|
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 liftUnary(_: type Result, operator: untyped) =
|
||||||
|
|
||||||
template `operator`*(a: ?!typed): ?!typed =
|
template `operator`*(a: ?!typed): ?!typed =
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
import std/unittest
|
import std/unittest
|
||||||
import std/sequtils
|
import std/sequtils
|
||||||
import std/strutils
|
import std/strutils
|
||||||
|
import pkg/questionable
|
||||||
import pkg/questionable/results
|
import pkg/questionable/results
|
||||||
|
|
||||||
suite "result":
|
suite "result":
|
||||||
@ -94,6 +95,10 @@ suite "result":
|
|||||||
check (40.success >= 42 == false.success)
|
check (40.success >= 42 == false.success)
|
||||||
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":
|
test "examples from readme work":
|
||||||
|
|
||||||
proc works: ?!seq[int] =
|
proc works: ?!seq[int] =
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user