Skip to content

Commit 6c8c657

Browse files
committed
Add map_or
1 parent a10e1a3 commit 6c8c657

File tree

4 files changed

+20
-2
lines changed

4 files changed

+20
-2
lines changed

NEWS.md

+5
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
## Release 0.5.1
2+
3+
__New features__
4+
* New function `map_or(f, x::Result, v)`. Returns `f(unwrap(x))` if x is a result value, else `v`
5+
16
## Release 0.5.0
27

38
__Breaking changes__

Project.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
name = "ErrorTypes"
22
uuid = "7f495686-c6d2-4c77-9e8e-e4c865675f9d"
33
authors = ["Jakob Nybo Nissen <[email protected]>"]
4-
version = "0.5.0"
4+
version = "0.5.1"
55

66
[compat]
77
julia = "1.3"

src/ErrorTypes.jl

+8-1
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,13 @@ function and_then(f, ::Type{T}, x::Result{O, E})::Result{T, E} where {T, O, E}
224224
Result{T, E}(data isa Ok ? Ok(f(data.x)) : Err(data.x))
225225
end
226226

227+
"""
228+
map_or(f, x::Result, v)
229+
230+
If `x` is a result value, return `f(unwrap(x))`. Else, return `v`.
231+
"""
232+
map_or(f, x::Result{O, E}, v) where {O, E} = f(@unwrap_or x return v)
233+
227234
"""
228235
unwrap_or(x::Result, v)
229236
@@ -266,7 +273,7 @@ base(x::Option{T}) where T = Some(@unwrap_or x (return nothing))
266273
export Ok, Err, Result, Option,
267274
is_error, some, none,
268275
unwrap, unwrap_error, expect, expect_error,
269-
and_then, unwrap_or, unwrap_error_or, flatten, base,
276+
and_then, unwrap_or, map_or, unwrap_error_or, flatten, base,
270277
@?, @unwrap_or, @unwrap_error_or
271278

272279
end

test/runtests.jl

+6
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,12 @@ using Test
8282
@test and_then(x -> abs(x) % UInt8, UInt8, Result{Int, Dict}(Ok(-55))) === Result{UInt8, Dict}(Ok(UInt8(55)))
8383
@test and_then(x -> x + 1, Bool, Result{String, Int}(Err(1))) === Result{Bool, Int}(Err(1))
8484
@test and_then(x -> "foo", Dict, Result{Int, Int}(Err(1))) === Result{Dict, Int}(Err(1))
85+
86+
# map_or
87+
@test map_or(x -> x + 1, Result{Float64, String}(Ok(3.0)), 3.0) === 4.0
88+
@test map_or(x -> x + 1, Result{Float64, String}(Err("foo")), 3.0) === 3.0
89+
@test map_or(x -> 0, Result{Int, Int}(Ok(5)), 1) === 0
90+
@test map_or(x -> 0, Result{Int, Int}(Err(19)), 1) === 1
8591
end
8692

8793
@testset "Option" begin

0 commit comments

Comments
 (0)