Skip to content

Commit

Permalink
Add Try.map (#48)
Browse files Browse the repository at this point in the history
  • Loading branch information
tkf authored Apr 24, 2022
1 parent 3a09700 commit abbf34e
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/src/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Try.unwrap
Try.unwrap_err
Try.oktype
Try.errtype
Try.map
```

## Short-circuit evaluation
Expand Down
3 changes: 3 additions & 0 deletions src/Try.jl
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ struct IsOkError <: InternalPrelude.Exception
InternalPrelude._IsOkError(ok) = new(ok)
end

function map end

macro and_return end
function var"@?" end
function var"@return" end
Expand All @@ -57,6 +59,7 @@ using .ExternalDocstrings: @define_docstrings

include("core.jl")
include("errortrace.jl")
include("tools.jl")
include("branch.jl")
include("show.jl")

Expand Down
25 changes: 25 additions & 0 deletions src/docs/map.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Try.map(f, result) -> result′
Try.map(f, Ok(value)) -> Ok(f(value))
Try.map(_, err::Err) -> err
Try.map(f, Some(value)) -> Some(f(value))
Try.map(_, nothing) -> nothing
Try.map(f) -> result -> Try.map(f, result)

Apply `f` in the value wrapped in the "successful" result.

# Examples

```julia
julia> using Try

julia> Try.map(x -> x + 1, Ok(1))
Try.Ok: 2

julia> Try.map(x -> x + 1, Err(KeyError(:a)))
Try.Err: KeyError: key :a not found

julia> Try.map(x -> x + 1, Some(1))
Some(2)

julia> Try.map(x -> x + 1, nothing)
```
23 changes: 23 additions & 0 deletions src/tools.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
Try.map(f, ok::Ok) = Ok(f(ok.value))
Try.map(_, err::Err) = err

function Try.map(f, result)
if Try.isok(result)
Ok(f(Try.unwrap(result)))
else
# Need to "forget" about any Ok value type information:
Err(Try.unwrap_err(result))
end
end

Try.map(f, some::Some) = Some(f(something(some)))
Try.map(_, ::Nothing) = nothing

struct TryMap{F} <: Function
f::F
end
TryMap(::Type{T}) where {T} = TryMap{Type{T}}(T)

(f::TryMap)(x) = Try.map(f.f, x)

Try.map(f::F) where {F} = TryMap(f)
7 changes: 7 additions & 0 deletions test/TryTests/src/test_tools.jl
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,11 @@ function test_macro()
@test demo_macro(1:0) === :oob
end

function test_map()
@test Try.map(x -> x + 1, Ok(1)) == Try.Ok(2)
@test Try.map(x -> x + 1, Err(KeyError(:a))) == Err(KeyError(:a))
@test Try.map(x -> x + 1, Some(1)) == Some(2)
@test Try.map(x -> x + 1, nothing) === nothing
end

end # module

0 comments on commit abbf34e

Please sign in to comment.